ReentrantLock

ReentrantLock:重入锁的意思。与synchronized作用差不多,区别就是synchronized加锁放锁看不见,而这个重入锁加锁放锁看的见

 1 package thread;
 2 
 3 import java.util.concurrent.locks.Lock;
 4 import java.util.concurrent.locks.ReentrantLock;
 5 
 6 public class 重入锁 {
 7     public static void main(String[] args) {
 8         T t = new T();
 9         Thread thread1 = new Thread(t);
10         Thread thread2 = new Thread(t);
11         Thread thread3 = new Thread(t);
12         thread1.start();
13         thread2.start();
14         thread3.start();
15 
16 
17     }
18 }
19 
20 class T implements Runnable {
21     private int count = 10;
22     private final ReentrantLock lock = new ReentrantLock();
23     @Override
24     public void run() {
25         while (true) {
26             try {
27                 // 加锁
28                 lock.lock();
29                 if (count > 0) {
30 
31                     try {
32                         Thread.sleep(1000);
33                     } catch (InterruptedException e) {
34                         e.printStackTrace();
35                     }
36                     System.out.println(--count);
37                 }
38             } finally {
39                 // 解锁
40                 lock.unlock();
41             }
42 
43 
44         }
45     }
46 }

一般把加锁解锁放在try finally语句里面包裹

posted on 2021-05-26 15:19  Love&Share  阅读(60)  评论(0编辑  收藏  举报

导航