一、简介
我们可以使用syncronized和wait,notify实现等待通知。而syncronized的高级实现Lock,也可以实现等待通知,需要构造Condition的实例对象。
JDK文档:http://tool.oschina.net/uploads/apidocs/jdk-zh/java/util/concurrent/locks/Condition.html
二、代码示例
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class ConditionDemo { private static ReentrantLock lock = new ReentrantLock(); private static Condition condition = lock.newCondition(); public static void main(String[] args) throws InterruptedException { new Thread(() -> { try { lock.lock(); condition.await(); System.out.println("end await"); lock.unlock(); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); Thread.sleep(3000); lock.lock(); condition.signal(); lock.unlock(); System.out.println("finished"); } }