非公平锁

非公平锁:

 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(false);
 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 }

运行结果如下:

  

猜你喜欢

转载自www.cnblogs.com/wang1001/p/9566887.html