मैं, जावालूप तुल्यकालन गतिरोध
public class Counter {
private int value;
public Counter(int value) {
this.value = value;
}
public void setValue(int value) {
this.value = value;
}
public void decrement() {
this.value--;
}
public int getValue() {
return this.value;
}
}
public class Cell extends Thread {
private Object sync;
private Counter counter;
public Cell(Object sync, Counter counter) {
this.sync = sync;
this.counter = counter;
}
public void run() {
for (int r=0; r<Simulation.ROUND_NUM; r++) {
// do something
synchronized(counter) {
counter.decrement();
counter.notifyAll();
}
synchronized(sync) {
try {
sync.wait();
}
catch (Exception ex) {}
}
}
}
}
public class Simulation extends Thread {
public static final int THREAD_NUM = 5;
public static final int ROUND_NUM = 5;
public Object sync = new Object();
private Counter counter = new Counter(THREAD_NUM);
public void run() {
for (int i=0; i<THREAD_NUM; i++) {
Cell c = new Cell(sync,counter);
c.start();
}
for (int i=0; i<ROUND_NUM; i++) {
synchronized(counter) {
while(counter.getValue() != 0) {
try {
counter.wait();
}
catch (Exception ex) {}
}
counter.setValue(THREAD_NUM);
}
synchronized(sync) {
sync.notifyAll();
}
}
}
}
उद्देश्य प्रत्येक सेल थ्रेड में पाश की अगले चरण को क्रियान्वित करने से रोकने के लिए है में निम्नलिखित वर्गों मिल गया है जब तक हर सेल थ्रेड प्रत्येक यात्रा पर किया जाएगा। मेरा समाधान कभी-कभी डेडलॉक की ओर जाता है। मैं समझ नहीं पा रहा हूं क्यों। कृपया
साइड नोट: यदि आपको स्पष्ट रूप से 'थ्रेड',' प्रतीक्षा 'और' सूचित करें '(और आप जावा 5 या बाद में उपयोग कर रहे हैं) का उपयोग करने की आवश्यकता नहीं है, तो आप एक ['CountDownLatch'] (http से बेहतर होंगे) : //download.oracle.com/javase/6/docs/api/java/util/concurrent/CountDownLatch.html) इसके बजाए। –