温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-07-29 23:14:06 来源:网络 阅读:585 作者:恋上程序员 栏目:编程语言
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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI