题目:
多线程按顺序打印10次ABC
package com.sy.day04.work_02;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @Author: ShenYang
* @Date: 2023-06-15-16:59
* @Description: TODO
* <p>
* comment:
* <p>
* 多线程按顺序打印10次ABC
**/
public class Test {
static int count = 10;
static int index =0;
public static void main(String[] args) {
Lock lock = new ReentrantLock();
Condition lock_A = lock.newCondition();
Condition lock_B = lock.newCondition();
Condition lock_C = lock.newCondition();
new Thread(new Runnable() {
@Override
public void run() {
lock.lock();
try {
while (true){
while (index!=0){
lock_A.await();
}
System.out.print("A");
lock_B.signal();
index=1;
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
lock.lock();
try {
while (true){
while (index!=1){
lock_B.await();
}
System.out.print("B");
lock_C.signal();
index=2;
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
lock.lock();
try {
while (true){
while (index!=2){
lock_C.await();
}
System.out.print("C ");
lock_A.signal();
index=0;
if (--count==0){
System.exit(1);
}
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}
}).start();
}
}