概述
它是锁(synchronized)的封装类,它更加的强大
互斥锁类
reentrantLock
监视器类
Condition(封装了一下Object中的监视器方法)
互斥锁方法
- .lock()
获得一个锁
- .unlock()
释放此锁
- .newCondition()
获取一个Condition监视器对象,用来进行线程通信
通过互斥锁线程通信示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| class Printer3 { private ReentrantLock r = new ReentrantLock(); private Condition c1 = r.newCondition(); private Condition c2 = r.newCondition(); private Condition c3 = r.newCondition(); private int flag = 1; public void print1() throws InterruptedException { r.lock(); if(flag != 1) { c1.await(); } System.out.print("加"); System.out.print("油"); System.out.print("加"); System.out.print("油"); System.out.print("!"); System.out.print("\r\n"); flag = 2; c2.signal(); r.unlock(); } public void print2() throws InterruptedException { r.lock(); if(flag != 2) { c2.await(); } System.out.print("加"); System.out.print("油"); System.out.print("加"); System.out.print("油"); System.out.print("\r\n"); flag = 3; c3.signal(); r.unlock(); } public void print3() throws InterruptedException { r.lock(); if(flag != 3) { c3.await(); } System.out.print("a"); System.out.print("b"); System.out.print("c"); System.out.print("d"); System.out.print("e"); System.out.print("f"); System.out.print("g"); System.out.print("\r\n"); flag = 1; c1.signal(); r.unlock(); } }
|