This is a class assignment where I need to use wait() and notify() in this code. The output I'm getting is:
Thread 0 is here
The output should be:
Thread 0 is here
Thread 1 is here
Thread 2 is here
Thread 3 is here
repeat above 9 more times.
When I debugged the code, the 2nd time wait() executes, the program stops completely.
Any help on how to get the correct output will be appreciated. If I need to clarify something, let me know.
Thank You
/** Experiment with threads.
* NOTE: there is no guarantee this will actually work as expected.
*/
public class MyThreadY extends Thread {
private static final int NUM_ITERS = 10;
//private static final int SLEEP_INCREMENT = 100; // 0.1 sec
private static int turn = 0;
private int myNumber;
private int total;
public MyThreadY(int num, int tot) {
this.myNumber = num;
this.total = tot;
}
public synchronized void run() {
for (int i=0; i<NUM_ITERS; i+=1) {
while (turn != myNumber)
try {
wait();
} catch (Exception ignored) {};
/* turn == myNumber */
System.out.println("Thread " + myNumber + " is here!");
turn = (turn + 1) % total; // let someone else have a turn...
notifyAll();
}
}
}

New Topic/Question
Reply




MultiQuote



|