第一种
public static volatile int flag = 1;
public static void printABC1(){
Thread t1 = new Thread(() -> {
while (true) {
synchronized (obj1) {
while (flag != 1){
try {
obj1.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
System.out.println("T1:A");
Thread.sleep(1000);
flag = 2;
obj1.notifyAll();
obj1.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread t2 = new Thread(() -> {
while (true) {
synchronized (obj1) {
while (flag != 2){
try {
obj1.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
System.out.println("T2:B");
Thread.sleep(1000);
flag = 3;
obj1.notifyAll();
obj1.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread t3 = new Thread(() -> {
while (true) {
synchronized (obj1) {
while (flag != 3){
try {
obj1.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
System.out.println("T3:C");
Thread.sleep(1000);
flag = 1;
obj1.notifyAll();
obj1.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t1.start();
t2.start();
t3.start();
}
第二种
public static ReentrantLock lock = new ReentrantLock();
public static Condition condition1 = lock.newCondition();
public static volatile int flag2 = 0;
public static void printABC2(){
Thread t1 = new Thread(() -> {
while (true){
lock.lock();
while (flag2 % 3 != 0){
try {
condition1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
System.out.println("T1:A");
Thread.sleep(1000);
flag2++;
condition1.signalAll();
condition1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
});
Thread t2 = new Thread(() -> {
while (true) {
lock.lock();
while (flag2 % 3 != 1){
try {
condition1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
System.out.println("T2:B");
Thread.sleep(1000);
flag2++;
condition1.signalAll();
condition1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
});
Thread t3 = new Thread(() -> {
while (true) {
lock.lock();
while (flag2 % 3 != 2){
try {
condition1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
System.out.println("T3:C");
Thread.sleep(1000);
flag2++;
condition1.signalAll();
condition1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
});
t1.start();
t2.start();
t3.start();
}