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开发者_JAVA技巧();
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!
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).
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
精彩评论