多线程打印之ReentrantLock

package com.zhang.reflection.面试.多线程打印;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ReentrantLock实现 {
    private int num;
    private Lock lock = new ReentrantLock();
    private void printABC(int targetNum) {
        for (int i = 0; i < 100; ) {
            lock.lock();
            if (num % 3 == targetNum) {
                num++;
                i++;
                System.out.print(Thread.currentThread().getName());
            }
            lock.unlock();
        }
    }
    public static void main(String[] args) {
        ReentrantLock实现 lockABC = new ReentrantLock实现();
        new Thread(() -> {
            lockABC.printABC(0);
        }, "A").start();
        new Thread(() -> {
            lockABC.printABC(1);
        }, "B").start();
        new Thread(() -> {
            lockABC.printABC(2);
        }, "C").start();
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
双非坐过牢:非佬,可以啊10.28笔试,11.06评估11.11,11.12两面,11.19oc➕offer
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务