This 0ne Pr0grammer
This 0ne Pr0grammer

Reputation: 2662

Use of Thread Count in Java GUI

So in this section of code I have, I want to essentially tell the GUI to disable the button and bring up a pop-up window when no threads are running anymore (i.e. the method called has finished).

public void actionPerformed(ActionEvent event) 
{
    String command = event.getActionCommand();

    //If btnConvertDocuments is clicked, the FileConverter method is called and the button is then disabled [so as to prevent duplicates].
    if (command.equals("w"))
    {
        new Thread(new Runnable() 
        {
            public void run() 
            {
                FileConverter fc = new FileConverter();

            }
         }).start();
        if (Thread.activeCount() == 0)
        {
            btnConvertDocuments.setEnabled(false);
            //Validation message ensuring completion of the step.
            JOptionPane.showMessageDialog(this, "Step 1 Complete!", "Validation", JOptionPane.INFORMATION_MESSAGE);
        }
    }

Why does that if (Thread.activeCount() == 0) never seem to get called? Is that not what I want to be doing in order to accomplish my objective? Thank you in advance for any input!

Upvotes: 1

Views: 757

Answers (2)

MByD
MByD

Reputation: 137382

There are many threads that are running when you run a Java program (for example, the main thread :) and look here) if you want to check the state of a thread, use the getState() method (just remember to assign the thread to a Thread variable:

        Thread t = new Thread(new Runnable() 
        {
            public void run() 
            {
                FileConverter fc = new FileConverter();

            }
         });
        t.start();
        if (t.getState().equals(Thread.State.TERMINATED) ) { ... }

Looking more into your question, you could call the join method as well, as it will block the current thread until t is done (or until timeout).

Upvotes: 2

mKorbel
mKorbel

Reputation: 109823

that's about Concurency in Swing, better would be wrap you BackGroung Task to the SwingWorker, very nice example by @Hovercraft Full Of Eels, or by implements Executor here

Upvotes: 2

Related Questions