Why does SwingWorker stop unexpectedly?

前端 未结 4 823
醉酒成梦
醉酒成梦 2020-12-07 01:19

I wanted to try out some ideas using SwingWorker since I haven\'t used it too much. Instead, I ran into an issue and I can\'t figure out what\'s wrong.

4条回答
  •  不知归路
    2020-12-07 02:10

    As already mentioned, you can use the UI to keep the threads alive.

    Alternatively, what you can do is use SwingWorker#get (or anything that prevents the main thread from terminating) to wait for the threads to finish. By doing so, you will get the output as expected. Here is the modified code, that does what you want.

    import javax.swing.SwingUtilities;
    import javax.swing.SwingWorker;
    import java.util.concurrent.ExecutionException;
    
    public class SwingWorkerTest
    {
        public static void main (String[] args)
        {
            final MySwingWorker w1 = new MySwingWorker (500),
             w2 = new MySwingWorker (900),
             w3 = new MySwingWorker (1200);
            SwingUtilities.invokeLater (new Runnable ()
            {
                @Override
                public void run ()
                {
                    w1.execute ();
                    w2.execute ();
                    w3.execute ();
                }
            });
    
            try{
                // you can replace the code in this block
                // by anything that keeps the program from 
                // terminating before the threads/SwingWorkers.
                w1.get();
                w2.get(); 
                w3.get(); 
            }catch(InterruptedException e){
                System.err.println("InterruptedException occured");
            }catch(ExecutionException e){
                System.err.println("InterruptedException occured");
            }
    
        }
    }
    
    class MySwingWorker extends SwingWorker
    {
        private int ms;
    
        public MySwingWorker (int ms)
        {
            this.ms = ms;
        }
    
        @Override
        protected Void doInBackground()
        {
            Thread t = Thread.currentThread ();
    
            for (int i = 0; i < 50; i++)
            {
                try
                {
                    Thread.sleep (ms);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace ();
                }
    
                System.out.println ("I am thread with " + ms + " sleep in iteration " + i + ": " + t.getName () + " (" + t.getId () + ")");
            }
    
            return null;
        }
    }
    

提交回复
热议问题