Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwingWorker thread not close even the task is finished?

I have a swingworker in my java project. I use netbean "profiler" to monitor the thread. I don't know why the swingworker thread still exist in the monitor of the profiler in NetBeans and it is in "Wait" State. In other words, if i click button b 10 times, there are 10 swingworker threads! Thank You.

  public static void main(String[] args) {
    // TODO code application logic here
    final JFrame f = new JFrame();
    f.setLayout(new BorderLayout());
    f.setSize(400, 400);
    b = new JButton("B1");      
    f.add(b,BorderLayout.CENTER);
    b.addActionListener(new ActionListener() {           
        @Override
        public void actionPerformed(ActionEvent e) {
           new SwingWorker() {

                @Override
                protected Object doInBackground() throws Exception {
                    return null;
                }
            }.execute();
        }
    });

    f.setVisible(true);
}
like image 478
Bear Avatar asked Jan 18 '23 18:01

Bear


1 Answers

To elaborate on my comment, check out the output from this modification of your code:

import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;

public class Foo002 {

   public static void main(String[] args) {
      final JFrame f = new JFrame();
      f.setLayout(new BorderLayout());
      f.setSize(400, 400);
      JButton b = new JButton("B1");
      f.add(b, BorderLayout.CENTER);
      b.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            new SwingWorker() {

               @Override
               protected Object doInBackground() throws Exception {
                  Thread current = Thread.currentThread();
                  System.out.printf("ID: %d, Name: %s%n", current.getId(), current.getName());
                  System.out.println("Active Count: " + Thread.activeCount());
                  return null;
               }
            }.execute();
         }
      });

      f.setVisible(true);
   }
}
like image 75
Hovercraft Full Of Eels Avatar answered Jan 30 '23 09:01

Hovercraft Full Of Eels