Java Reference
In-Depth Information
public class CountingTask implements Runnable {
private static int COUNTER = 0;
private int threadId;
public CountingTask() {
threadId = ++COUNTER;
}
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("Thread #"+threadId+" is at: "+i);
try {
// Rest a bit to give other threads a chance to work
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Thread thread1 = new Thread(new CountingTask());
Thread thread2 = new Thread(new CountingTask());
thread1.start();
thread2.start();
}
}
If you try to execute this code, you'll note that both threads' output lines will end up mixed on the
console. This shows how threads can serve as a helpful way to define multiple work tasks within the
same program. Note that your operating system is responsible for the actual allocation of CPU time
to the various threads in your program. Even if you have only one CPU core, the operating system
will make sure to divide calculation time so that each thread in all running programs on your com-
puter get a chance to do their work, causing them to seemingly run in parallel. Note that running
the code snippet above actually involves the creation of three threads: the main thread (all programs
have one main thread, where the main method is invoked) and the two custom-defined ones.
Let's return to the discussion of the Event Dispatch Thread (EDT). This thread is started in the
background (i.e., next to the main thread) to continually process events: button clicks, mouse clicks,
and so on. Whenever you write code that makes changes to the GUI of a program, all this code
must be executed in this Event Dispatch Thread as well. Updating visible components from other
threads is the source of many common bugs in Java programs that use Swing. Note that this aspect
is not specific to Swing; the same concept exists in other UI toolkits as well. To see how updating the
UI outside the EDT can cause problems, take a look at the following code:
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
public class MultiThreadedFrame extends JFrame {
public static final int LENGTH = 100;
Search WWH ::




Custom Search