刚才看到一个博客(http://wangxinchun.iteye.com/blog/1859250)里写了一道面试题:
启动三个线程,分别打印A B C,现在写一个程序 循环打印ABCABCABC....
原文中有很多实现方法。
我感觉如果可以用Java5以后的Semaphore实现的话会比较简单,于是写了一个实现:
package org.devside.study.synchronous;
import java.util.concurrent.Semaphore;
/**
* User: matianyi
* Date: 13-5-4
* Time: 下午8:58
*/
public class ThreadSync {
static class ConditionThread extends Thread {
ConditionThread(Semaphore preCond, Semaphore postCond, String text) {
this.preCond = preCond;
this.postCond = postCond;
this.text = text;
}
private Semaphore preCond;
private Semaphore postCond;
private String text;
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
preCond.acquire();
System.out.print(text);
postCond.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Semaphore semaphoreA = new Semaphore(0);
Semaphore semaphoreB = new Semaphore(0);
Semaphore semaphoreC = new Semaphore(1);
Thread threadA = new ConditionThread(semaphoreC, semaphoreA, "A");
Thread threadB = new ConditionThread(semaphoreA, semaphoreB, "B");
Thread threadC = new ConditionThread(semaphoreB, semaphoreC, "C");
threadA.start();
threadB.start();
threadC.start();
threadA.join();
threadB.join();
threadC.join();
}
}