简体   繁体   中英

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 background", 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. Eg,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM