【并发编程领域】3个线程依序打印ABC

 大体思路:借助juc中Lock+Condition实现,通过一个变量来标志执行哪一个线程 condition中唤醒对应的线程。ABC线程形成一个环形 A-》B-》C-》A 如此反复就可以

/**
 * @author i
 * @create 2019/12/29 16:03
 * @Description  ABC线程每次依序打印 ABCABC循环 10次
 */
class MyShareData{

    private Integer count = 0;
    private Lock lock = new ReentrantLock();
    private Condition cA = lock.newCondition();
    private Condition cB = lock.newCondition();
    private Condition cC = lock.newCondition();

    public void printA(){
        try {
            //1.判断
            lock.lock();
            while (count != 0){
                cA.await();//等待
            }
            //2.工作
            System.out.println(Thread.currentThread().getName()+"\t A");
            //3.唤醒其他线程
            count = 1;
            cB.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void printB(){
        try {
            //1.判断
            lock.lock();
            while (count != 1){
                cB.await();//等待
            }
            //2.工作
            System.out.println(Thread.currentThread().getName()+"\t B");
            //3.唤醒其他线程
            count = 2;
            cC.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void printC(){
        try {
            //1.判断
            lock.lock();
            while (count != 2){
                cC.await();//等待
            }
            //2.工作
            System.out.println(Thread.currentThread().getName()+"\t C");
            //3.唤醒其他线程
            count = 0;
            cA.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}

public class SynAndReentrantLockDemo {

    public static void main(String[] args) {
        MyShareData myShareData = new MyShareData();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                myShareData.printA();
            }
        },"t1").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                myShareData.printB();
            }
        },"t2").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                myShareData.printC();
            }
        },"t3").start();
    }

}

 

全部评论

相关推荐

11-09 12:17
清华大学 C++
out11Man:小丑罢了,不用理会
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务