When writing a threaded program you can pretend that you're writing many different programs, each with its own run()
method.
Each thread is a subclass of java.lang.Thread
.
The following program is a thread that prints the
numbers between -128 and 127.
public class BytePrinter extends Thread {
public void run() {
for (int b = -128; b < 128; b++) {
System.out.println(b);
}
}
}
You launch this thread from another method, probably in another class,
by instantiating an object of this class using new
and calling its start()
method.
To create a thread just call the default constructor for your subclass of Thread
. For instance
BytePrinter bp = new BytePrinter();
This class only has the default, noargs constructor; but there's absolutely no reason you can't add other constructors to
your Thread
subclass.
Constructing a thread object puts it at the starting line. The bell goes off and the thread starts running when you call the thread's start()
method like this:
bp.start();
Once the start()
method is called program execution splits in two. Some CPU time goes into whatever statements follow bp.start()
and some goes into the bp
thread. It is unpredictable which statements will run first. Most likely they will be intermixed. The bp
thread will now continue running until one of seven things happens
bp
's run()
method completes.
bp
's stop()
method is called.
bp
's suspend()
method is called.
bp
's sleep()
method is called.
bp
's yield()
method is called.
bp
blocks waiting for an unavailable resource
bp
's run()
method the thread dies. It cannot be restarted, though you can create a
new instance of the same Thread
subclass and start that.