I copied this code below from a tutorial and pasted it in my editor (Netbeans 8.1). I read the SwingWorker documentation and from what I understand from this and other documents is that the execute() method is suppose to "start the thread" (or puts it in a worker thread).
public class Sandbox {
public static void main(String[] args)
{
SwingWorker<Void, Void> w = new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
for(int i=0; i<=10; i++){
Thread.sleep(1000);
System.out.println(i);
}
return null;
}
};
w.execute();
}
}
What is the problem here? If I use SwingUtilities.invokeLater(w) it works, but it only displays 0, and when I remove the Thread.sleep(1000) (which as far as I know, is suppose to pause things), it works as expected.
SwingWorker does use daemon threads (here in form of worker threads). The Java Virtual Machine itself exits when the only threads running are all daemon threads. So in your program, you reach the end of your main method and your program gets terminated. See the API:
public final void execute()
Schedules this SwingWorker for execution on a worker thread. There are a number of worker threads available.
When removing the Thread.sleep, your computer may be fast enough to execute the loop before the JVM exits.
You can wait for your SwingWorker to finish with the get method, though this will block your main thread.