多线程循环打印ABC
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
public static ReentrantLock Lock = new ReentrantLock();
public static Condition ConditionA = Lock.newCondition();
public static Condition ConditionB = Lock.newCondition();
public static Condition ConditionC = Lock.newCondition();
public static char next = 'A';
public static void main(String[] args) {
Thread threadA = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10; i++) {
Lock.lock();
try {
while (next != 'A') {
ConditionA.await();
}
System.out.println("A");
next = 'B';
ConditionB.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
Lock.unlock();
}
}
}
});
Thread threadB = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10; i++) {
Lock.lock();
try {
while (next != 'B') {
ConditionB.await();
}
System.out.println("B");
next = 'C';
ConditionC.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
Lock.unlock();
}
}
}
});
Thread threadC = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10; i++) {
Lock.lock();
try {
while (next != 'C') {
ConditionC.await();
}
System.out.println("C");
next = 'A';
ConditionA.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
Lock.unlock();
}
}
}
});
threadA.start();
threadB.start();
threadC.start();
}
}
标签:ABC,Java,Thread,Lock,打印,next,static,new,public
From: https://www.cnblogs.com/DCFV/p/18391249