码迷,mamicode.com
首页 > 编程语言 > 详细

java ReentrantLock 公平锁 非公平锁 测试

时间:2019-02-11 12:48:44      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:tac   src   test   boolean   private   bsp   col   OLE   void   

 1 package reentrantlock;
 2 
 3 import java.util.ArrayList;
 4 import java.util.concurrent.locks.ReentrantLock;
 5 
 6 public class TestFairSyn {
 7 
 8     public static void main(String[] args) {
 9         ArrayList<Thread> arrayList = new ArrayList<>();
10         Resrc resrc = new Resrc();
11 
12         for (int i = 0; i < 15; i++){
13             arrayList.add(new Thread(resrc));
14         }
15         for (int i = 0; i < 15; i++){
16             arrayList.get(i).start();
17         }
18     }
19 
20     static class Resrc implements Runnable{
21         private static boolean isTestFair = true;
22         ReentrantLock reentrantLock = new ReentrantLock(isTestFair);
23 
24         @Override
25         public void run() {
26             System.out.println(Thread.currentThread().getId()+" 尝试获得锁");
27             reentrantLock.lock();
28             if (false){
29                 System.out.println("\t\t" + Thread.currentThread().getId() + " 成功获得锁-解锁");
30                 reentrantLock.unlock();
31             }
32             else {
33                 try {
34                     System.out.println("\t\t" + Thread.currentThread().getId() + " 成功获得锁");
35                     // 如果测试 公平锁,把睡眠时间取消,能够大大增加线程的抢占现象
36                     Thread.sleep(0, 100);
37                 } catch (InterruptedException e) {
38                     e.printStackTrace();
39                 } finally {
40                     System.out.println("\t\t" + "\t\t" + Thread.currentThread().getId() + " 解锁");
41                     reentrantLock.unlock();
42                 }
43             }
44         }
45     }
46 
47 }

 

java ReentrantLock 公平锁 非公平锁 测试

标签:tac   src   test   boolean   private   bsp   col   OLE   void   

原文地址:https://www.cnblogs.com/cnblogszs/p/10361387.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!