公平锁

2018-09-01 05:42:39来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

公平锁:

 1 import java.util.concurrent.locks.ReentrantLock;
 2 
 3 public class Service {
 4     
 5     private ReentrantLock lock;
 6     
 7     public Service(boolean isFair) {
 8         lock = new ReentrantLock();
 9     }
10 
11     public void serviceMethod() {
12         try {
13             lock.lock();
14             System.out.println(Thread.currentThread().getName() + "获取的锁");
15         } finally {
16             lock.unlock();
17         }
18     }
19 }
 1 public class Run {
 2 
 3     /**
 4      *    公平锁
 5      */
 6     public static void main(String[] args) {
 7         final Service service = new Service(true);
 8         
 9         Runnable runnable = new Runnable() {
10             @Override
11             public void run() {
12                 System.out.println("线程:" + Thread.currentThread().getName());
13                 service.serviceMethod();
14             }
15         };
16         
17         Thread[] threads = new Thread[10];
18         for (int i = 0; i < 10; i++) {
19             threads[i] = new Thread(runnable);
20         }
21         for (int i = 0; i < 10; i++) {
22             threads[i].start();
23         }
24     }
25 }

运行结果如下:

  

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Map.putAll方法

下一篇:JavaWeb开发SSM框架搭建详解