一 原始构成
二 使用方法
三 等待是否可中断
四 加锁是否公平
五 锁绑定多个条件condition
代码:
精确通知:
public class ShareResource {
private int number = 1; //a:1 b:2 c:3
private Lock lock = new ReentrantLock();
private Condition condition1 = lock.newCondition();
private Condition condition2 = lock.newCondition();
private Condition condition3 = lock.newCondition();
public void print5(){
lock.lock();
try {
while (number != 1){
condition1.await();
}
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()+"打印:"+i);
}
number = 2;
//精确通知
condition2.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void print10(){
lock.lock();
try {
while (number != 2){
condition2.await();
}
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+"打印:"+i);
}
number = 3;
condition3.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void print15(){
lock.lock();
try {
while (number != 3){
condition3.await();
}
for (int i = 0; i < 15; i++) {
System.out.println(Thread.currentThread().getName()+"打印:"+i);
}
number = 1;
condition1.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
public class LockDemo {
public static void main(String[] args) {
ShareResource shareResource = new ShareResource();
for (int i = 0; i < 2; i++) {
new Thread(new Runnable() {
@Override
public void run() {
shareResource.print5();
}
},"A"+i).start();
}
for (int i = 0; i < 2; i++) {
new Thread(new Runnable() {
@Override
public void run() {
shareResource.print10();
}
},"B"+i).start();
}
for (int i = 0; i < 2; i++) {
new Thread(new Runnable() {
@Override
public void run() {
shareResource.print15();
}
},"C"+i).start();
}
}
}
结果:实现的精确唤醒。
A0打印:0
A0打印:1
A0打印:2
A0打印:3
A0打印:4
B0打印:0
B0打印:1
B0打印:2
B0打印:3
B0打印:4
B0打印:5
B0打印:6
B0打印:7
B0打印:8
B0打印:9
C0打印:0
C0打印:1
C0打印:2
C0打印:3
C0打印:4
C0打印:5
C0打印:6
C0打印:7
C0打印:8
C0打印:9
C0打印:10
C0打印:11
C0打印:12
C0打印:13
C0打印:14
A1打印:0
A1打印:1
A1打印:2
A1打印:3
A1打印:4
B1打印:0
B1打印:1
B1打印:2
B1打印:3
B1打印:4
B1打印:5
B1打印:6
B1打印:7
B1打印:8
B1打印:9
C1打印:0
C1打印:1
C1打印:2
C1打印:3
C1打印:4
C1打印:5
C1打印:6
C1打印:7
C1打印:8
C1打印:9
C1打印:10
C1打印:11
C1打印:12
C1打印:13
C1打印:14
A2打印:0
A2打印:1
A2打印:2
A2打印:3
A2打印:4
B2打印:0
B2打印:1
B2打印:2
B2打印:3
B2打印:4
B2打印:5
B2打印:6
B2打印:7
B2打印:8
B2打印:9
C2打印:0
C2打印:1
C2打印:2
C2打印:3
C2打印:4
C2打印:5
C2打印:6
C2打印:7
C2打印:8
C2打印:9
C2打印:10
C2打印:11
C2打印:12
C2打印:13
C2打印:14
A3打印:0
A3打印:1
A3打印:2
A3打印:3
A3打印:4
B3打印:0
B3打印:1
B3打印:2
B3打印:3
B3打印:4
B3打印:5
B3打印:6
B3打印:7
B3打印:8
B3打印:9
C3打印:0
C3打印:1
C3打印:2
C3打印:3
C3打印:4
C3打印:5
C3打印:6
C3打印:7
C3打印:8
C3打印:9
C3打印:10
C3打印:11
C3打印:12
C3打印:13
C3打印:14
A4打印:0
A4打印:1
A4打印:2
A4打印:3
A4打印:4
B4打印:0
B4打印:1
B4打印:2
B4打印:3
B4打印:4
B4打印:5
B4打印:6
B4打印:7
B4打印:8
B4打印:9
C4打印:0
C4打印:1
C4打印:2
C4打印:3
C4打印:4
C4打印:5
C4打印:6
C4打印:7
C4打印:8
C4打印:9
C4打印:10
C4打印:11
C4打印:12
C4打印:13
C4打印:14