需求:有三个线程轮流执行,第一个线程打印A,第二个线程打印B,第三个线程打印C……循环10次。
思路:三个线程共享同一把锁、一个线程轮流状态state。线程拿到锁之后,通过state进行判断,如果轮到当前线程打印,则执行打印、更改state状态。每个线程都不停的循环,获取锁、判断state,执行打印,并……直到每个线程打印10次。
效率:由于三个线程不停的抢占锁,但是获取锁后不一定具备打印条件,所以性能比较低。
实现代码:
package edu.self.multithread;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created by SunYanhui on 2017/12/6.
*/
public class MultipleThreadRotationUsingExplicitLock {
public static void main(String[] args) {
PrintABCUsingReentrantLock printABC = new PrintABCUsingReentrantLock();
new Thread(() -> printABC.printA()).start();
new Thread(() -> printABC.printB()).start();
new Thread(() -> printABC.printC()).start();
}
}
class PrintABCUsingReentrantLock {
private Lock lock = new ReentrantLock();
private int state = 0;
//private int attempts =0;
public void printA() {
print("A", 0);
}
public void printB() {
print("B", 1);
}
public void printC() {
print("C", 2);
}
private void print(String name, int currentState) {
for (int i = 0; i < 10; ) {
lock.lock();
try {
//System.out.println(Thread.currentThread().getName()+" try to print "+name+", attempts : "+(++attempts));
while (state % 3 == currentState) {
System.out.println(Thread.currentThread().getName() + " print " + name);
state++;
i++;
}
}finally {
lock.unlock();
}
}
}
}