I want to wait() the put() method called from the second thread which has been connected to the Server (Monitor). But when i do this, the whole GUI frames (Swing) including their elements get frozen aftr the second put() call. How to fix this? I want the second thread keep waiting till the first thread performs a get() which frees a slot. Thanks in advance. Here's my skeleton code:
Server:
Buffer<String> buf = new Buffer<String>(1);
while(true){
//for each socket connected
new ServerHandler(..., buf).start();
}
ServerHandler:
public class ServerHandler extends Thread {
Buffer<Messenger> buf;
public void run(){
buf.put("Test");
}
}
Buffer:
public class BufferImp<String>
private String[] requests;
private int cur_req_in; // current Request in the queue
private int req_size;
private int req_count;
public BufferImp(int size) {
this.req_size = size;
requests = new String[size];
this.cur_req_in = 0;
this.req_count = 0;
}
public synchronized void put(E o) throws InterruptedException {
while(req_size == req_count) this.wait();
requests[cur_req_in] = o;
cur_req_in = (cur_req_in + 1) % req_size;
req_count++;
notifyAll();
}
}
This happens if you wait() in the AWT-EventQueue thread. You should never wait there (no new events can be handled and gui frezes). Use a SwingWorker instead which waits for the response.
-> http://download.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html
Don't call wait when code is executing on the Event Dispatch Thread.
Instead you need to create a separate Thread for your long running task,
Read the section from the Swing tutorial on Concurrency for more information.