在閱讀有關信號量之後,我嘗試了這個測試代碼,我在其中創建了兩個線程A和B.我的目標是,讓線程A等待線程B中某些操作的10秒完成。但是由於我稍微改變了線程B中的邏輯,通過引入一個永遠不會出現的無限循環,線程A也掛起,並且程序永遠運行。任何人都可以幫助我實現我期待的目標嗎?信號量和線程問題
包裝;
import java.util.concurrent.Semaphore;
public class Concurrency {
public int count = 0;
public static void main(String args[]) throws Exception {
final Semaphore sem = new Semaphore(1, true);
Thread thrdA, thrdB;
thrdA = new Thread(new Runnable() {
@Override
public void run() {
synchronized (sem) {
try {
sem.wait(10000);
System.out.println("thread1");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thrdB = new Thread(new Runnable() {
@Override
public void run() {
synchronized (sem) {
System.out.println("thread2");
while(true){
}
}
}
});
thrdA.start();
thrdB.start();
thrdA.join();
thrdB.join();
}
}
爲什麼你在使用'Semaphore'如果你從來沒有'acquire()'然後'release()'它呢?你可以爲此使用一個'private final Object'。 – corsiKa 2011-12-22 06:08:56