import java.util.*;
import java.util.concurrent.locks.LockSupport;
public class test {
static Thread threadA, threadB, threadC;
public static void main(String[] args) {
threadA = new Thread(() -> {
System.out.print("A");
LockSupport.unpark(threadB);
LockSupport.park();
});
threadB = new Thread(() -> {
LockSupport.park();
System.out.print(Thread.currentThread().getName());
LockSupport.unpark(threadC);
}, "B");
threadC = new Thread(() -> {
LockSupport.park();
System.out.print(Thread.currentThread().getName());
LockSupport.unpark(threadA);
}, "C");
threadA.start();
threadB.start();
threadC.start();
}
}
使用信号量交替打印ABC(打印10次)
static class Printer implements Runnable {
private char letter;
private Semaphore currentSemaphore;
private Semaphore nextSemaphore;
public Printer(char letter, Semaphore currentSemaphore, Semaphore nextSemaphore) {
this.letter = letter;
this.currentSemaphore = currentSemaphore;
this.nextSemaphore = nextSemaphore;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
// 获取当前信号量的许可
currentSemaphore.acquire();
System.out.print(letter);
// 释放下一个信号量的许可
nextSemaphore.release();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
public static void main(String[] args) {
Thread threadA = new Thread(new Printer('A', semaphoreA, semaphoreB));
Thread threadB = new Thread(new Printer('B', semaphoreB, semaphoreC));
Thread threadC = new Thread(new Printer('C', semaphoreC, semaphoreA));
threadA.start();
threadB.start();
threadC.start();```