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

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

发布时间:2020-07-29 23:14:06

来源:51CTO

阅读:461

作者:恋上程序员

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值