廖雪峰Java11多线程编程-3高级concurrent包-3Condition
1.Condition实现等待和唤醒线程
java.util.locks.ReentrantLock用于替代synchronized加锁
但是synchronized可以使用wait和notify实现线程在条件不满足时的等待,条件满足时的唤醒。
如何使用ReentrantLock实现wait/notify的功能?
这个时候我们可以使用Condition对象来实现条件不满足时的等待,条件满足时的唤醒。
class TaskQueue{
final Lock lock = new ReentrantLock()
final Condition notEmpty = lock.newCondition();
}
1.1 对Condition对象调用await()方法就相当于对所对象调用wait()方法。
![](https://img2018.cnblogs.com/blog/1418970/201906/1418970-20190612221123891-1658768634.png)
![](https://img2018.cnblogs.com/blog/1418970/201906/1418970-20190612221535147-1998887621.png)
2. 示例
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class TaskQueue{
final Queue<String> queue = new LinkedList<>();
final Lock lock = new ReentrantLock();
final Condition notEmpty = lock.newCondition();
public String getTask() throws InterruptedException{
lock.lock();
try{
while(this.queue.isEmpty()){
notEmpty.await();
}
return queue.remove();
}finally {
lock.unlock();
}
}
public void addTask(String name){
lock.lock();
try{
this.queue.add(name);
notEmpty.signalAll();
}finally {
lock.unlock();
}
}
}
class WorkerThread extends Thread{
TaskQueue taskQueue;
public WorkerThread(TaskQueue taskQueue){
this.taskQueue = taskQueue;
}
public void run(){
while(!isInterrupted()){
String name;
try{
name = taskQueue.getTask();
}catch (InterruptedException e){
break;
}
String result = "Hello, "+name+" !";
System.out.println(result);
}
}
}
public class Main{
public static void main(String[] args) throws InterruptedException{
TaskQueue taskQueue = new TaskQueue();
WorkerThread worker = new WorkerThread(taskQueue);
worker.start();
taskQueue.addTask("Bob");
Thread.sleep(1000);
taskQueue.addTask("Alice");
Thread.sleep(1000);
taskQueue.addTask("Tim");
Thread.sleep(1000);
worker.interrupt();
worker.join();
System.out.println("END");
}
}
![](https://img2018.cnblogs.com/blog/1418970/201906/1418970-20190612213304879-1521626218.png)