大橙子网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

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

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

创新互联-专业网站定制、快速模板网站建设、高性价比铁锋网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式铁锋网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖铁锋地区。费用合理售后完善,10年实体公司更值得信赖。

Process finished with exit code 0


当前标题:JAVA多线程按指定顺序执行线程Condition应用
文章出自:http://dzwzjz.com/article/ieodpe.html
在线咨询
服务热线
服务热线:028-86922220
TOP