码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA多线程按指定顺序执行线程 Condition应用

时间:2019-08-01 17:27:23      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:try   with   ack   多线程   ESS   stat   auth   sign   tac   

package concurrent; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; /** * Auth: zhouhongliang * Date:2019/8/1 * 线程等待与唤醒机制 Condition * 按指定顺序执行线程 */ public class ConditionDemo { public static void main(String[] args) { //声明重入锁 ReentrantLock reentrantLock = new ReentrantLock(); //声明Condition对象 final Condition condition1 = reentrantLock.newCondition(); final Condition condition2 = reentrantLock.newCondition(); final Condition condition3 = reentrantLock.newCondition(); new Thread(() -> { //加锁 reentrantLock.lock(); try { //等待 condition1.await(); System.out.println("AA"); } catch (InterruptedException e) { e.printStackTrace(); } finally { //解锁 reentrantLock.unlock(); } }).start(); new Thread(() -> { reentrantLock.lock(); try { condition2.await(); System.out.println("BB"); condition1.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally { reentrantLock.unlock(); } }).start(); new Thread(() -> { reentrantLock.lock(); try { condition3.await(); System.out.println("CC"); condition2.signal(); } catch (InterruptedException e) { e.printStackTrace(); } finally { reentrantLock.unlock(); } }).start(); new Thread(() -> { reentrantLock.lock(); try { System.out.println("DD"); //唤醒 condition3.signal(); } catch (Exception e) { e.printStackTrace(); } finally { reentrantLock.unlock(); } }).start(); } }

输出结果:
DD
CC
BB
AA

Process finished with exit code 0

JAVA多线程按指定顺序执行线程 Condition应用

标签:try   with   ack   多线程   ESS   stat   auth   sign   tac   

原文地址:https://blog.51cto.com/11147669/2425610

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!