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.