Condition 显式条件
显式条件在不同上下文中也可以被称为条件变量、条件队列、或条件
锁用于解决竞态条件问题,条件是线程间的协作机制。显式锁与synchronized相对应,而显式条件与wait/notify相对应。wait/notify与synchronized配合使用,显式条件与显式锁配合使用。条件与锁相关联,创建条件变量需要通过显式锁,Lock接口定义了创建方法:
1 | Condition newCondition(); |
Condition表示条件变量,是一个接口,它的定义为:
1 2 3 4 5 6 7 8 9 | public interface Condition { void await() throws InterruptedException; void awaitUninterruptibly(); long awaitNanos( long nanosTimeout) throws InterruptedException; boolean await( long time, TimeUnit unit) throws InterruptedException; boolean awaitUntil(Date deadline) throws InterruptedException; void signal(); void signalAll(); } |
await对应于Object的wait, signal对应于notify, signalAll对应于notifyAll,语义也是一样的。
使用显式条件进行协作的示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | public class WaitThread extends Thread { private volatile boolean fire = false ; private Lock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); @Override public void run() { try { lock.lock(); try { while (!fire) { condition.await(); } } finally { lock.unlock(); } System.out.println( "fired" ); } catch (InterruptedException e) { Thread.interrupted(); } } public void fire() { lock.lock(); try { this .fire = true ; condition.signal(); } finally { lock.unlock(); } } public static void main(String[] args) throws InterruptedException { WaitThread waitThread = new WaitThread(); waitThread.start(); Thread.sleep( 1000 ); System.out.println( "fire" ); waitThread.fire(); } } |
参考: Java编程的逻辑 16.3 显式条件
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2018-01-25 js判断一个字符串是以某个字符串开头
2018-01-25 如何 通过 userAgent 区别微信小程序