每日一问 - 两个线程交替打印 ABAB (三)
使用 Semaphore
实现 ABAB 交替打印
public class ABSemHolder {
private Semaphore semaphoreA = new Semaphore(1);
private Semaphore semaphoreB = new Semaphore(0);
public void printA() throws InterruptedException {
semaphoreA.acquire();
System.out.print("A");
semaphoreB.release(); // permit + 1
}
public void printB() throws InterruptedException {
semaphoreB.acquire();
System.out.print("B");
semaphoreA.release();
}
}
测试
public static void abLoop() throws InterruptedException {
final ABSemHolder holder = new ABSemHolder();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
holder.printA();
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
holder.printB();
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t1.start();
t2.start();
}
结果:
ABABABABABABABABABABABABABABABABAB
Process finished with exit code -1