多个线程线程顺序打印:标序号,顺序打印。
下面程序使用可重入锁ReentranceLock。每个线程的打印部分循环了十次,循环打印的核心操作由lock控制。
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class test {
private int times = 10;
// 启动四个线程
private int count = 4;
// 控制转移状态值
private volatile int state;
private Lock lock = new ReentrantLock();
public static void main(String[] args) {
test test = new test();
new Thread(() -> test.print("A", 0)).start();
new Thread(() -> test.print("B", 1)).start();
new Thread(() -> test.print("C", 2)).start();
new Thread(() -> test.print("D", 3)).start();
}
private void print(String name, int targetState) {
// 每个线程打印10次
for (int i = 0; i < times; ) {
try {
lock.lock();
if (state % count == targetState) {
state++;
i++;
System.out.print(name);
}
} catch (UnsupportedOperationException e) {
} finally {
lock.unlock();
}
}
}
}
参照:多个线程顺序打印问题