Condition的作用用一句话概括就是为了实现线程的等待(await)和唤醒(signal),ReentrantLock+Condition的组合使用相当于synchronized+Object.wait/notify。
1. 使用
public class ConditionTest {
public static ReentrantLock reentrantLock = new ReentrantLock();
public static Condition condition = reentrantLock.newCondition();
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new MyThread0());
thread.start();
Thread.sleep(2000);
reentrantLock.lock();
System.out.println("main lock");
condition.signal();
System.out.println("main signalAll unlock");
reentrantLock.unlock();
}
public static class MyThread0 implements Runnable{
@Override
public void run() {
reentrantLock.lock();
try {
System.out.println(Thread.currentThread().getName() + " await");
condition.await(); // 挂起线程并释放锁
System.out.println(Thread.currentThread().getName() + " await end");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
- 输出结果
out =>
Thread-0 await
main lock
main signalAll unlock
Thread-0 await end
网友评论