跳到主要内容

手搓代码

两个线程交替打印 A B,一共打印

信号量

public class Main {
final static Semaphore semaphoreA = new Semaphore(1);
final static Semaphore semaphoreB = new Semaphore(0);

public static void main(String[] args) {
Thread threadA = new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
semaphoreA.acquire(1);
System.out.println("A");
semaphoreB.release();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});

Thread threadB = new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
semaphoreB.acquire(1);
System.out.println("B");
semaphoreA.release();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});

threadA.start();
threadB.start();
threadA.join();
threadB.join();
}
}