Copyright Derek O'Reilly, Dundalk Institute of Technology (DkIT), Dundalk, Co. Louth, Ireland.
A thread is a process that shares an address space and processor time with other threads. Each thread processes its program code independently.
Any class that extends the Thread class is a thread.
A thread's:
|
override this. It contains the processing code of a thread. |
|
|
calls run() |
|
|
causes a thread to wait for a given length of time |
|
|
returns true if a thread has been started |
|
|
interrupts a thread that is sleeping |
|
|
Returns true if a thread has been interrupted |
A thread is ideal for running background multimedia activities such as animations, sounds and marquees.
Although the Thread class contains a stop(), suspend() and resume() method, they are no longer used. The proper way to stop a Thread prior to its normal termination is by interrupting it, as shown in the example below.
Thread_Marquee_Demo Example (Run Applet)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Thread_Marquee_Demo extends JApplet
{
@Override
public void init()
{
this.setContentPane(new View());
}
public class View extends JPanel implements ActionListener
{
private final JButton startStop = new JButton("START");
private final MarqueeCanvas marqueeCanvas;
private MarqueeThread marqueeThread;
public View()
{
super();
this.marqueeCanvas = new MarqueeCanvas("Scrolling Text", 200);
this.setLayout(new BorderLayout());
this.add("Center", this.marqueeCanvas);
this.add("South", this.startStop);
this.startStop.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e)
{
if (this.startStop.getText().equals("START"))
{
this.marqueeThread = new MarqueeThread(this.marqueeCanvas);
this.marqueeThread.start();
this.startStop.setText("STOP");
}
else // this.startStop.getText() == "STOP"
{
this.marqueeThread.interrupt();
this.startStop.setText("START");
}
}
}
public class MarqueeThread extends Thread
{
private MarqueeCanvas marqueeCanvas;
public MarqueeThread(MarqueeCanvas marqueeCanvas)
{
this.marqueeCanvas = marqueeCanvas;
}
@Override
public void run()
{
try
{
while (!interrupted())
{
this.marqueeCanvas.incrementPos();
this.sleep(10); // 10/1000th = 1/100th second
}
}
catch (InterruptedException e)
{
}
}
}
public class MarqueeCanvas extends JPanel
{
private String message;
private int minX;
private int curX;
private int maxX;
private int y;
public MarqueeCanvas(String message, int width)
{
this.message = message;
this.y = 20;
this.curX = 0;
this.minX = 0;
this.maxX = width;
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g); // clear the background
g.drawString(this.message, this.curX, this.y);
}
public void incrementPos()
{
if (++this.curX >= this.maxX)
{
this.curX = this.minX;
}
this.repaint();
}
}
}
Copyright Derek O' Reilly, Dundalk Institute of Technology (DkIT), Dundalk, Co. Louth, Ireland.