使用Lock
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ABCLock2 {
private static Lock lock = new ReentrantLock();
private static Condition A = lock.newCondition();
private static Condition B = lock.newCondition();
private static Condition C = lock.newCondition();
class printA implements Runnable{
@Override
public void run() {
try {
lock.lock();
for (int i = 0; i < 10; i++) {
System.out.print(i+" A");
B.signal();
if (i<9)
A.await();
}
}catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
class printB implements Runnable{
@Override
public void run() {
try {
lock.lock();
for (int i = 0; i < 10; i++) {
System.out.print("B");
C.signal();
if (i<9)
B.await();
}
}catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
class printC implements Runnable{
@Override
public void run() {
try {
lock.lock();
for (int i = 0; i < 10; i++) {
System.out.println("C");
A.signal();
if (i<9)
C.await();
}
}catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
public static void main(String[] args) {
ABCLock2 p = new ABCLock2();
new Thread(p.new printA()).start();
new Thread(p.new printB()).start();
new Thread(p.new printC()).start();
}
}