Using Thread waiting() method
I am trying to send a notify to an available Thread (first Thread i can find in a pool currently in a WAITING state), but am unable to. I am trying to send the notify alert to a thread running in a separate class, although this class is included in the same package. Here is the Server.java file from which I am trying to notify my available thread:
***************Server.java***********************
Code :
package dir.test;
import java.util.ArrayList;
import java.util.LinkedList;
public class Server {
static private final int THREADCOUNT=5;
public static void main(String[] args) throws InterruptedException {
ArrayList<Thread> objThreads = new ArrayList<Thread>(THREADCOUNT);
for (int i=0; i<THREADCOUNT; i++) {
objThreads.add(i, new Thread(new ObjThread(1)));
objThreads.get(i).start();
}
try {
for (int i=0; i<objThreads.size(); i++) {
if ( (objThreads.get(i).getState())==Thread.State.WAITING ) {
System.out.println("Thread " + i + " is in state: WAITING.");
objThreads.get(i).notify();
System.out.println("Thread " + i + " has been notified.");
}
}
} catch (Exception e) {
e.printStackTrace();
} catch (Throwable t) {
System.err.println("Caught throwable t: " + t);
}
}
}
**********************************************
and here's the ObjThread.java file...
***************ObjThread.java********************* **
Code :
package dir.test;
import java.lang.Runnable;
import java.util.*;
public class ObjThread implements Runnable {
private int int_var;
public ObjThread(int int_var) {
this.int_var = int_var;
}
public synchronized void run() {
while ( true ) {
try {
System.out.println("test...before wait");
wait();
System.out.println("test...after wait. int variable value: " + int_var);
} catch ( InterruptedException e ) { }
}
}
}
**********************************************
The thread never gets to the statement:
System.out.println("test...after wait. int variable value: " + int_var);
My output is:
$ java dir.test.Server
test...before wait
test...before wait
test...before wait
test...before wait
test...before wait
Thread 0 is in state: WAITING.
java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at dir.test.Server.main(Server.java:23)
Any idea how I can wake a thread from a WAITING state with this file structure so it can resume it's work?
Re: Using Thread waiting() method
Acquire a lock on the objects...flank the wait and notify by a synchronized statement on the object you are calling prior to calling these methods.