public class Thread05 {
public static void main(String[] args) {
Data05 data = new Data05();
new Thread(()-> {
while (true) {
data.m1();
}
}, "A").start();
new Thread(()-> {
while (true) {
data.m2();
}
}, "B").start();
}
}
// 说明:生产者、消费者、线程之间通信
// 注意:Condition是依赖Lock对象的。Condition在调用方法之前必须获取锁。
class Data05 {
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
int number = 0;
public void m1() {
lock.lock();
try {
if (number == 1) {
condition.await(); // 等待
}
number++;
System.out.println(Thread.currentThread().getName() + "生产完成");
condition.signalAll(); // 唤醒全部
} catch (Exception e){
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void m2() {
lock.lock();
try {
if (number == 0) {
condition.await();
}
number--;
System.out.println(Thread.currentThread().getName() + "生产完成");
condition.signal();
} catch (Exception e){
e.printStackTrace();
} finally {
lock.unlock();
}
}
}