SwingWorker: when exactly is called done method?

后端 未结 6 2093
遇见更好的自我
遇见更好的自我 2020-12-05 10:50

Javadoc of the done() method of SwingWorker:

Executed on the Event Dispatch Thread after the doInBackground method is

6条回答
  •  没有蜡笔的小新
    2020-12-05 11:14

    done() is called in any case, wether the worker is cancelled or it finishes normally. Nevertheless there are cases where the doInBackground is still running and the done method is called already (this is done inside cancel() no matter if the thread already finished). A simple example can be found here:

    public static void main(String[] args) throws AWTException {
        SwingWorker sw = new SwingWorker() {
    
            protected Void doInBackground() throws Exception {
                System.out.println("start");
                Thread.sleep(2000);
                System.out.println("end");
                return null;
            }
    
            protected void done() {
                System.out.println("done " + isCancelled());
            }
        };
        sw.execute();
        try {
            Thread.sleep(1000);
            sw.cancel(false);
            Thread.sleep(10000);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    

    Thus it can be the case that done is called before doInBackground finishes.

提交回复
热议问题