- Condition可以替代wait/notify
Condition.await/signal/sigalAll原理和wait/notify/notifyAll一致
await()会释放当前锁,进入等待状态
signal()会唤醒某个等待线程
signalAll()会唤醒所有等待线程
唤醒线程从await()返回后需要重新获得锁 - Condition对象必须从ReentrantLock对象获取
- ReentrantLock+Condition可以替代synchronized+wait/notify
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 Exception{
lock.lock();
try{
while(this.queue.isEmpty()){
notEmpty.await();
}
return queue.remove();
}finally {
lock.unlock();
}
}
public void addTask(String name) throws Exception{
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=null;
try{
name=taskQueue.getTask();
}catch (InterruptedException e){
break;
} catch (Exception e) {
e.printStackTrace();
}
String result="Hello "+name;
System.out.println(result);
}
}
}
public class ConcurrentCondition {
public static void main(String[] args) throws Exception{
TaskQueue taskQueue=new TaskQueue();
WorkerThread workerThread=new WorkerThread(taskQueue);
workerThread.start();
taskQueue.addTask("bob");
Thread.sleep(1000);
taskQueue.addTask("lucy");
Thread.sleep(1000);
taskQueue.addTask("zhang");
Thread.sleep(1000);
workerThread.interrupt();
workerThread.join();
System.out.println("Main End");
}
}