所有 Swing 框架都被“冻结”当 Java 中调用 wait() 时
我想 wait() 从已连接到服务器(监视器)的第二个线程调用 put() 方法。但是当我这样做时,整个 GUI 框架(Swing)包括它们的元素在第二次 put() 调用后被冻结。如何解决这个问题?我希望第二个线程继续等待,直到第一个线程执行释放插槽的 get() 。提前致谢。这是我的框架代码:
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();
}
}
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();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您在 AWT-EventQueue 线程中 wait(),就会发生这种情况。你永远不应该在那里等待(无法处理新事件并且 GUI 冻结)。使用 SwingWorker 来等待响应。
-> http://download.oracle.com/javase/6 /docs/api/javax/swing/SwingWorker.html
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
当代码在事件分派线程上执行时,不要调用 wait。
相反,您需要为长时间运行的任务创建一个单独的线程,
请阅读 Swing 教程中关于 并发了解更多信息。
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.