多个线程顺序执行


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestSequential01{
private static Lock lock = new ReentrantLock ();
private static Condition[] conditions = {lock.newCondition (),lock.newCondition (),lock.newCondition ()};
private volatile int state = 1;

private void run(final int self) {
int next = self % 3 + 1;
while (true) {
lock.lock ();
try {
while (this.state != self) {
conditions[self - 1].await ();
}
System.out.println (self);
this.state = next;
conditions[next - 1].signal ();
} catch (InterruptedException e) {
e.printStackTrace ();
}
lock.unlock ();
}
}

public static void main(String[] args) {
TestSequential01 rlc = new TestSequential01 ();
for (int i = 1;i < 4;i++) {
int j = i;
new Thread (() -> rlc.run (j)).start ();
}
}
}
原文地址:https://www.cnblogs.com/sunny-miss/p/14991704.html