Files are available by executing ~classque/JavaThreads on the CS network.
There are two main ways to use threads in Java:
Create an object with a class which extends the class Thread
The constructor initializes the thread.
When the thread's start method is called, the thread's
run method executes concurrently with other threads.
Create an object of type Thread.
The constructor has a parameter that is an object from a class that
implements Runnable.
When the thread is started, the run method of that
Runnable object is executed.
Often, the Runnable is the same object that creates the thread.
When you declare a Thread variable with Thread ping
the variable is initially null.
(This is true for any reference variable.)
If an class implements Runnable it must have a run
method. Executing: ping = new Thread(this)
creates a new thread which can execute the run method of the class.
The thread can be started with its start method: ping.start();
At this point the thread is in its active state. It remains active
until it is stopped or it completes execution of its run method.
Ping Pong Application
PingPong.java
is a thread that prints out a word a given number
of times with a given delay.
It also shows the number of active threads.
PingPongTest1.java
is an application that just starts two copies of PingPong.
Using join
Join suspends the caller until the thread has completed.
The PingPongTest2
application waits for each thread to complete and
then prints a message.
It also has a method which shows the threads.
Thread States
new: The thread has been created but not started, for example with
t = new Thread(this);
runnable: The thread has been started and is in the ready queue.
running: The thread is actually running on a CPU.
suspended: The thread's suspend method has been called
while the thread was runnable or running.
It makes no further progress until its resume method is called.
blocked: The thread is blocked from continuing because it requested
I/O, called sleep, called wait, or called join.
suspended-blocked: A blocked thread was suspended by another thread
calling its suspend method.
dead: The thread has terminated because it has completed its run
method or its stop method has been called.