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();
}
}