java - thread.sleep() within SwingWorker

2019-09-01 08:01发布

问题:

I am just wondering if the following code is correct. I have a SwingWorker that does something, sleeps, does something else and updates GUI. Is it okay to use Thread.sleep inside SwingWorker?

class MySwingy extends SwingWorker<Void, Void> {

    @Override
    public Void doInBackground() {

        //Do Something

        try {
            Thread.sleep(200);
        } catch (Exception ex) {
        }

        //Do Something

    }

    @Override
    public void done() {
        //Update GUI
    }
}

回答1:

If you really need to, there is no technical reason why you can't do that. The thread that will block is a background thread and your UI will not block.

But may I ask why you need to sleep in a background thread? Maybe your design can be improved to remove that need?