Lock
Posted shun-w
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Lock相关的知识,希望对你有一定的参考价值。
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() + " " + 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() + " " + 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() + " " + number);
}
number=1;
c1.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
以上是关于Lock的主要内容,如果未能解决你的问题,请参考以下文章