标签:exception class nts unlock wait vat exce rac print
JVM提供了synchronized关键字来实现对变量的同步访问以及用wait和notify来实现线程间通信。在jdk1.5以后,JAVA提供了Lock类来实现和synchronized一样的功能,并且还提供了Condition来显示线程间通信。
c1打印完通知c2,c2打印完通知c3
class Hello {
private int number = 1;//A:1, B:2, C:3
private Lock lock = new ReentrantLock();
private Condition c1 = lock.newCondition();
private Condition c2 = lock.newCondition();
private Condition c3 = lock.newCondition();
//判断
public void print5() {
lock.lock();
try {
while (number != 1) {
c1.await();
}
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + "\t" + number);
}
number=2;
c2.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void print10() {
lock.lock();
try {
while (number != 2) {
c2.await();
}
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "\t" + number);
}
number=3;
c3.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void print8() {
lock.lock();
try {
while (number != 3) {
c3.await();
}
for (int i = 0; i < 8; i++) {
System.out.println(Thread.currentThread().getName() + "\t" + number);
}
number=1;
c1.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
标签:exception class nts unlock wait vat exce rac print
原文地址:https://www.cnblogs.com/shun-w/p/12337127.html