Hi all
I read somewhere that the notify() method must be called by another
thread.
Thus, If anyone could enlighten me I was wondering why in this
piece of code at //1 I can't seem to get Counter A out of the
waiting state.
Thanks
Alex
------------------------------
class Counter extends Thread {
private int currentValue;
private static boolean flag;
public Counter(
String threadName) {
super(threadName);
currentValue = 0;
System.out.println(this);
start();
}
public void run() {
while (currentValue < 5) {
System.out.println(getName() + ": " + (currentValue++));
getSynchronized();
}
System.out.println("Exit from " + getName() + ".");
}
public int getValue() { return currentValue; }
public synchronized void getSynchronized(){
System.out.println("I am synchonized!");
try{
if (!flag){
System.out.println("waiting");
flag = true;
wait();
}
else {
System.out.println("I didn't wait");
notify(); //1
}
}
catch(InterruptedException e){ System.out.println("Interrupted");}
}
}
public class TestClient {
public static void main(String args[]) {
Counter cA = new Counter("Counter A");
cA.setPriority(10);
Counter cB = new Counter("Counter B");
try {
System.out.println("Wait for the child threads to finish.");
cA.join();
cB.join();
if (!cA.isAlive())
System.out.println("Counter A not alive.");
if (!cB.isAlive())
System.out.println("Counter B not alive.");
} catch (InterruptedException e) {
System.out.println("Main Thread interrupted.");
}
System.out.println("Exit from Main Thread.");
}
}
[This message has been edited by Alexander Black (edited May 18, 2001).]