If you ask how to do something with threads people will tell you "do not use threads." Or they might even ask the question, "why do you want to use threads?" And depending on your answer, they will proceed to tell you not to use threads.
This is sound advice in some regards, so you try to avoid threads, and you start writing an application with a gui. You create a listener, somebody pushes a button and voila you hang your gui until your action is complete because you are working on the EDT. The solution... use a thread.
The goal of this article is to setup a thread that you does your work while keeping your program "single threaded."
For starters, what is the EDT?
This picture shows the netbeans profiler view when I run a very simple swing program. The program I used just creates a JFrame and shows it. For this simple program there are 9 threads. Honestly I am familiar with two, though I could make an educated guess for the rest of them. The important one is the EventQueue, it processes events in a serial fashion, and the main thread is where we enter our program.
Threading is not so hard as it is complicated. These complications give rise to techniques and language that need to be known when dealing with threads. This is part of the challenge of learning threads, or teaching threads. Using the names correctly. A Queue is like waiting in line, so as events are generated appropriate actions are put in line, and the EventQueue executes these actions in a serial fashion.
Here is my simple example of a frame, with a button and a label.
public class SimpleFrame { public static void main(String[] args){ JFrame frame = new JFrame("threaded application"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400,400); final JLabel label = new JLabel("display"); final JButton button = new JButton("name"); button.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent event){ label.setText(Thread.currentThread().getName()); } }); JPanel content = new JPanel(); content.add(label); content.add(button); frame.setContentPane(content); frame.setVisible(true); } }
When the button is clicked the name of the thread will pop up, which is:
AWT-EventQueue-0
What that means is that we are executing our code on the EDT. So the next step is to get off of the EDT.