多线程交替打印之ReentrantLock+Condition

package com.zhang.reflection.面试.多线程打印;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ReentrantLock和Condition实现 {
    private int num;
    private static Lock lock = new ReentrantLock();
    private static Condition c1 = lock.newCondition();
    private static Condition c2 = lock.newCondition();
    private static Condition c3 = lock.newCondition();

    private void printABC(int targetNum, Condition currentThread, Condition nextThread) {
        for (int i = 0; i < 100; ) {
            lock.lock();
            try {
                while (num % 3 != targetNum) {
                    currentThread.await();  //阻塞当前线程
                }
                num++;
                i++;
                System.out.print(Thread.currentThread().getName());
                nextThread.signal();    //唤醒下一个线程
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        ReentrantLock和Condition实现 reentrantLockConditionAbc = new ReentrantLock和Condition实现();
        new Thread(() -> {
            reentrantLockConditionAbc.printABC(0, c1, c2);
        }, "A").start();
        new Thread(() -> {
            reentrantLockConditionAbc.printABC(1, c2, c3);
        }, "B").start();
        new Thread(() -> {
            reentrantLockConditionAbc.printABC(2, c3, c1);
        }, "C").start();
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
11-27 10:48
点赞 评论 收藏
分享
11-13 20:32
门头沟学院 Java
面向未来编程code:我没看到他咋急,他不就问你个问题。。。
点赞 评论 收藏
分享
废铁汽车人:秋招真是牛鬼蛇神齐聚一堂
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务