public class ConditionDemo {
private static final ReentrantLock lock = new ReentrantLock();
private static final Condition condition = lock.newCondition();
private static boolean flag = true;
public static void main(String[] args) throws Exception {
Thread waitThread = new Thread(new Waiter(), "Wait Thread");
waitThread.start();
Thread.sleep(1000);
Thread notifyThread = new Thread(new Notifier(), "Notify Thread");
notifyThread.start();
}
private static class Waiter implements Runnable {
@Override
public void run() {
lock.lock();
try {
while (flag) {
System.out.println(Thread.currentThread() + " flag is true. wait @ " +
new SimpleDateFormat("HH:mm:ss").format(new Date()));
condition.await();
}
System.out.println(Thread.currentThread() + " flag is false. running @ " +
new SimpleDateFormat("HH:mm:ss").format(new Date()));
} catch (InterruptedException e) {
System.out.println(e.getMessage());
} finally {
lock.unlock();
}
}
}
private static class Notifier implements Runnable {
@Override
public void run() {
lock.lock();
try {
System.out.println(Thread.currentThread() + " hold lock. notify @ " +
new SimpleDateFormat("HH:mm:ss").format(new Date()));
condition.signalAll();
flag = false;
Thread.sleep(5000); // Thread.sleep() 不会释放锁
System.out.println(Thread.currentThread() + " hold lock again. sleep @ " +
new SimpleDateFormat("HH:mm:ss").format(new Date()));
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
} finally {
lock.unlock();
}
}
}
}
输出:
Thread[Wait Thread,5,main] flag is true. wait @ 15:25:39
Thread[Notify Thread,5,main] hold lock. notify @ 15:25:40
Thread[Notify Thread,5,main] hold lock again. sleep @ 15:25:45
Thread[Wait Thread,5,main] flag is false. running @ 15:25:50
join test
Process finished with exit code 0
和上一篇文章差不多,不过是把 Object 类型的对象 lock 换成了 Condition,使用方式也是相近的
Condition.await() 同样会释放锁