Condition ReentrantLock循环10次打印ABC

package org.luzhen.test;

import java.awt.image.VolatileImage;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: luzhen
 * @Date: 2019-02-12 13:09
 * @Version 1.0
 */
public class ConditionTest {

    static Lock lock = new ReentrantLock();
    final static Condition condition1 = lock.newCondition();
    final static Condition condition2 = lock.newCondition();
    final static Condition condition3 = lock.newCondition();
    private volatile int state = 0;


    public static void main(String[] args) {
        ConditionTest conditionTest = new ConditionTest();
        
        new Thread(() -> {
            conditionTest.printA("A", 0,1, condition1, condition2);
        }).start();

        new Thread(() -> {
            conditionTest.printA("B", 1,2, condition2, condition3);
        }).start();

        new Thread(() -> {
            conditionTest.printA("C", 2,0, condition3, condition1);
        }).start();
    }

    /**
     * 
     * @param s 打印的字符串内容
     * @param inParameter 初始化的state入参值
     * @param expectNextState 控制打印顺序的开关 让对应的哪个线程执行打印
     * @param currentCondition 由于3个condition 会创建3个阻塞队列 代表当前condition所对应的那个阻塞队列
     * @param nextCondition 通知我们规定的那个线程 从对应的等待队列里进入同步队列中 获取锁 执行打印
     */
    public void printA(String s, int inParameter,int expectNextState, Condition currentCondition, Condition nextCondition) {
        for (int i = 0; i < 10; i++) {
            try {
                lock.lock();
                while (state != inParameter) {
                    currentCondition.await();
                }
                System.out.println(s);
                state = expectNextState;
                nextCondition.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}

打印效果:

A
B
C

A
B
C

A
B
C

A
B
C

A
B
C

A
B
C

A
B
C

A
B
C

A
B
C

A
B
C

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值