所有的Swing帧都被“冻结".在Java中调用wait()时 [英] All the Swing frames get "frozen" when wait() is called in Java

查看:106
本文介绍了所有的Swing帧都被“冻结".在Java中调用wait()时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想 wait()从连接到服务器(监视器)的第二个线程调用的 put()方法.但是,当我这样做时,整个GUI框架(Swing)及其元素将在第二次put()调用后冻结.如何解决这个问题?我希望第二个线程一直等待,直到第一个线程执行get()来释放插槽.提前致谢.这是我的基本代码:

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:

服务器:

Buffer<String> buf = new Buffer<String>(1);
while(true){
   //for each socket connected           
   new ServerHandler(..., buf).start();

}

ServerHandler:

ServerHandler:

public class ServerHandler extends Thread {

  Buffer<Messenger> buf;

  public void run(){
      buf.put("Test");
  }
}

缓冲区:

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();


    }
}

推荐答案

在事件调度线程上执行代码时,请不要等待.

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,

并发上的Swing教程中阅读本节,更多信息.

Read the section from the Swing tutorial on Concurrency for more information.

这篇关于所有的Swing帧都被“冻结".在Java中调用wait()时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆