开发者

Threads in GUI (Swing) - application unfreeze

I have a question regarding threads in Java Swing Application. There's a module in my app which receives and sends email messages. I'd like to assign an action to a Button (mouseClicked) to receive unread emails.

Pseudo-code:

ExchangeConnector ec = new ExchangeConnector();
ArrayList<Mail> unreadMails = ec.receive(Mail.UNREAD);
// (...)
ec.close();

My current implementation makes application freeze, until receiving is complete (sometimes it could take more than 10 minutes).

The question is - how to make it completely "in bac开发者_运维技巧kground", making my application usable for other actions?


Have a look at the SwingWorker for doing this kind of thing off the Swing Thread.

SwingWorker is:

useful when a time-consuming task has to be performed following a user-interaction event


Johan Sjöberg gave the hint: put the long-running task into a thread. I further want to add: don't start different threads (unless you really need to do), but instead use one dedicated worker thread for such operations. Otherwise you will get lost in thread-nirvana. Keeping an eye on two threads (event dispatch thread and worker thread) is much simpler.


Instead of blocking the swing thread, create a new thread to perform the receive for you. E.g.,

new Thread(new EmailReceiver(new ExchangeConnector())).start();

And the EmailReceiver

public class EmailReceiver implements Runnable {
     private ExchangeConnnector ec;

     public EmailReceiver(ExchangeConnector ec) {
         this.ec = ec;
     }

     @Override
     public void run() {
         ec.receive(Mail.UNREAD);
     }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜