Condition控制线程通信
对象 | 等待 | 唤醒 | 唤醒所有 |
---|---|---|---|
Object | wait() | notify() | notifyAll() |
Condition | await() | signal() | signalAll() |
Lock同步锁的线程通信需要通过Condition实现
通过Lock+Condition实现上一节最后的生产者消费者案例
package com.atguigu.juc;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 售货员从啤酒厂上货,张三买货
*/
public class TestProductorAndConsumer {
public static void main(String[] args) {
Clerk clerk = new Clerk();
Productor productor = new Productor(clerk);
Consumer consumer = new Consumer(clerk);
new Thread(productor, "啤酒厂").start();
new Thread(consumer, "张三").start();
new Thread(productor, "烟厂").start();
new Thread(consumer, "李四").start();
}
}
/**
* 售货员
*/
class Clerk{
private int product = 0;
Lock lock = new ReentrantLock();
// Condition实例实质上被绑定到了一个锁上,要为特定的Lock实例获得Condition实例,需要使用newCondition()方法
Condition condition = lock.newCondition();
public void get(){
lock.lock();
try {
while (product >= 1){
System.out.println("产品已满!");
try {
// 告知啤酒厂库存满了
// this.wait();
condition.await();
} catch (InterruptedException e) {
}
}
System.out.println("从" + Thread.currentThread().getName() + "上新货 : " + ++product);
// 通知张三新货到了
// this.notifyAll();
condition.signalAll();
}finally {
lock.unlock();
}
}
public void sale(){
lock.lock();
try {
while (product <= 0){
System.out.println("缺货!");
try {
// 告知张三没货了
// this.wait();
condition.await();
} catch (InterruptedException e) {
}
}
System.out.println(Thread.currentThread().getName() + "买了啤酒" + product--);
// 通知啤酒厂,又卖掉货了,有空位了,可以生产啤酒了
// this.notifyAll();
condition.signalAll();
}finally {
lock.unlock();
}
}
}
/**
* 啤酒厂
*/
class Productor implements Runnable{
private Clerk clerk;
Productor(Clerk clerk){
this.clerk = clerk;
}
@Override
public void run() {
for (int i = 1; i <= 3; i++) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
this.clerk.get();
}
}
}
/**
* 消费者
*/
class Consumer implements Runnable{
private Clerk clerk;
Consumer(Clerk clerk){
this.clerk = clerk;
}
@Override
public void run() {
for (int i = 1; i <= 3; i++) {
this.clerk.sale();
}
}
}
标签:JUC,Thread,lock,控制线,Lock,new,public,Condition
From: https://www.cnblogs.com/wzzzj/p/18045241