Java Reference
In-Depth Information
The Class Thread
In Java, a thread is an object of the class Thread . The normal way to program a thread
is to define a class that is a derived class of the class Thread . An object of this derived
class will be a thread that follows the programming given in the definition of the
derived (thread) class.
Where do you do the programming of a thread? The class Thread has a method
named run . The definition of the method run is the code for the thread. When the
thread is executed, the method run is executed. Of course, the method defined in the
class Thread and inherited by any derived class of Thread does not do what you want
your thread to do. So, when you define a derived class of Thread , you override the def-
inition of the method run to do what you want the thread to do.
In Display 19.2 the inner class Packer is a derived class of the class Thread . The method
run for the class Packer is defined to be exactly the same as the method fill in our previ-
ous, unresponsive GUI (Display 19.1). So, an object of the class Packer is a thread that
will do what fill does, namely draw the circles to fill up a portion of the window.
The method actionPerformed in Display 19.2 differs from the method
actionPerformed in our older, nonresponsive program (Display 19.1) in that the
invocation of the method fill is replaced with the following:
Thread
run()
start()
Packer packerThread = new Packer( );
packerThread.start( );
This creates a new, independent thread named packerThread and starts it process-
ing. Whatever packerThread does, it does as an independent thread. The main thread
can then allow actionPerformed to end and the main thread will be ready to respond
to any click of the close-window button.
Display 19.2 Threaded Version of FillDemo (part 1 of 3)
1
import javax.swing.JFrame;
The GUI produced is identical to
the GUI produced by Display 19.1
except that in this version the
close-window button works even
while the circles are being drawn,
so you can end the GUI early if you
get bored.
2
import javax.swing.JPanel;
3
import javax.swing.JButton;
4
import java.awt.BorderLayout;
5
import java.awt.FlowLayout;
6
import java.awt.Graphics;
7
import java.awt.event.ActionListener;
8
import java.awt.event.ActionEvent;
9
public class ThreadedFillDemo extends JFrame implements ActionListener
10
{
11
public static final int WIDTH = 300;
12
public static final int HEIGHT = 200;
13
public static final int FILL_WIDTH = 300;
14
public static final int FILL_HEIGHT = 100;
15
public static final int CIRCLE_SIZE = 10;
16
public static final int PAUSE = 100; //milliseconds
(continued)
Search WWH ::




Custom Search