SwingWorker not responding

后端 未结 3 1880
攒了一身酷
攒了一身酷 2020-11-28 16:35

What I am trying to do ?

At the click of the Start JButton, the SwingWorker will execute. Inside the doInBackground(

3条回答
  •  执念已碎
    2020-11-28 17:06

    if I add Thread.sleep(...), it does work, though, it throws a InterruptedException

    The code that apparently produces the exception (copied from OP's edit):

    while (!isCancelled()) {
        counter %= arrNames.length;
        // System.out.format("Counter : %d%n", counter);
        publish(arrNames[counter]);
        try {
            Thread.sleep(30); // throws
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        }
        counter++;
    }
    

    The reason, though, is the code that cancels the worker (in the actionListener):

    backgroundTask.cancel(true);
    

    which explicitly tells the worker to cancel by .. interrupting the thread. From its api doc:

    mayInterruptIfRunning - true if the thread executing this task should be interrupted; otherwise, in-progress tasks are allowed to complete

    As an aside: catching the exception and doing nothing (thereby effectively ignoring the interrupt) is not the best of ideas. Probably not too damaging in this case - due to checking the cancelled status. Typical worker implementations either catch and return, after doing some internal cleanup if needed, or don't handle it at all.

提交回复
热议问题