Java Thread: First Steps
(Free Web Tutorials)
by Michael Thomas
Java Thread Home Page
In this tutorial you will discuss Java Thread(s) and do several
code-walkthroughs.
Note: On the Java Threads Home page, you can download
the whole Java Threads site (all content, tutorials & examples) !!!
In the tutorial download zip file, another zip file containing the java source
code is located in the sub directory: \tutorial_firststeps_thread\eclipseprojects\zip
This tutorial covers: Java Threads as of Java 1.6 (last
updated 06/30/08)
Prerequisites
- JDK installed.
- This tutorials has been tested in the following environment:
Date: 07/04/08
OS: Win XPro
JDK: jdk1.6.0_03
Objectives
- Create a Java Thread by sub-classing Thread.
- Create a Java Thread by implementing Runnable.
- Create multiple Java Threads from one Java application.
- Understand how to start a Thread and override it's run() method.
- Discuss concurrency concepts.
- Describe how the start() & run() interact.
- Use the Thread.sleep() & Thread.join() methods.
- See an example of how a thread can decide what to do when an interrupt
is received.
- Understand how to use the methods: interrupted() , wait() and
notify().
- Create a class that will wait & notify the proper threads to set and get
values between them.
- Understand how to synchronize a method or a block of code.
What is a Java Thread?
A Java Thread is a lightweight process that runs inside of a Java program
(process) that has it's own execution context allowing a Java program to do more
than one thing at a time (multiple threads running concurrently). From the
developers point of view, every Java program has at least one thread called the
main thread.
Why use a Java Thread?
- Allow your Java program to do more than one task at a time (concurrent
programming). For example, a user can interact with your program while
in the background your programs is doing another task like downloading a
file, streaming audio etc...
Concurrency Concepts
- The OS handles the execution of processes and threads in an execution
core.
- Computers can have 1 or more CPU's (Central Processing Units).
- Every CPU has at least 1 execution core. An execution core can
execute commands.
- A CPU may support an OS feature where there is more than one
execution core per CPU.
- For a specific execution core only one Thread can be executed at a
time.
- If the computer has 1 CPU with a single execution core then multiple
process and threads is executed by using the concept of time slicing.
- To see the processes running in Windows XP go to the Control Panel,
Administrative Tools, Services.
- There are two types of concurrent execution: processes and threads.
- Each process has its own run-time environment: memory, etc...
- Every process has at least 1 thread.
- Every java program has at least one process that has at least 1 thread
called the "main" thread.
- Threads run within a process and therefore are called lightweight
processes.
- Within a process, threads have their own execution environment but it
has fewer resources and they share some of the process's resources: memory,
open files, etc...
- A Java program is a process.
- A software application may have 1 or more Java programs that make up
the application.
- One Java program may communicate to another Java program through
pipes and sockets.
- Within your Java program there are system threads that handle management
functions like memory management.
The Thread Object
- A thread is an instance of the "Thread" object.
- Here are some of the common ways to create a Thread.
- Implement the "Runnable" interface.
- Most popular because it is flexible.
- It's flexible because you can subclass any desired class.
- Subclass the "Thread" class.
- Not as popular because it is not as flexible as implementing "Runnable"
however it is very easy to create.
- Not as flexible because your class must subclass "Threads".
- Timers
- java.util.Timer & java.util.TimerTask
- javax.swing.Timer
- Thread support such behaviors as starting, sleeping, being interrupted,
yielding, joining and having a priority.
- The "Thread" class extends the "Object" class supports behaviors as
waiting and notifying.
Implementing the "Runnable" interface
Implementing the "Runnable" interface is the most flexible way to create a
thread because you can subclass any desired class.
-
Objectives
- Create a thread by implementing the "Runnable" interface
- Understand what the Thread's start() method does
- Become familiar with creating an a thread from an anonymous class
- Understand how the Thread's run() method gets called
- Discuss thread execution order when treads have equal priorities
- Be aware that the JVM will give the object a name if one is not
specified.
-
ThreadsHelloWorldWaysRunnable.java.txt - Hello World example of implementing the
Runnable
interface.
Here is an example of the java console results:
Thread-0 - Hello World from a thread! (implement Runnable)
ThreadHW2 - Hello World from a thread! (implement Runnable)
ThreadHW1 - Hello World from a thread! (implement Runnable)
ThreadAnonymousClass - Hello World from a thread! (anonymous class) (implement Runnable)
- Right click on the link(s) above and open in a new window so we can do
a
code-walkthrough.
- This class implements the Runnable interface:
ex: public class ThreadsHelloWorldRunnable implements Runnable
- When this class is executed by java.exe the "main" method will run
first.
- main() then does the following:
- Creates a new thread named: ThreadHW1
- Creates "objRunnable" which is an
instance of the class "ThreadsHelloWorldRunnable"
- Creates "objThreadHW1" which is an instance of Thread
created from the object "objRunnable".
- At this point we have created our Thread.
- objThreadHW.start() - this starts the Thread which eventually calls
the run() method of "objRunnable". Our run method overrides the
Runnable's run method which actually does nothing.
- Creates a new thread named: ThreadHW2
- This code is an example of creating the thread and executing
.start() in one line of code.
- Creates a new thread from an anonymous class.
- This code is an example of create a thread from an anonymous class
and executing .start() in one line of code.
- Notice that this anonymous class has it's own run() method that
prints to the screen. The anonymous class must override the run()
method.
- The class constructor - we could have removed this code from the
class because we are not using it.
- start() - this method makes the thread active and then calls the
run() method.
- run() - this method get's the name of the thread and then writes out
to the console a message.
- Execution order - there is no guarantee to the order in which
threads will get CPU time to execute their code (especially if equal
priorities).
- If you look at the java console results below you will notice that
the threads wrote to the screen in the following order:
Thread-0,
ThreadHW2,
ThreadHW1,
ThreadAnonymousClass.
- The main() created and started the classes in a different order:
ThreadHW1,
ThreadHW2,
Thread-0,
ThreadAnonymousClass.
- Finished the code walkthrough.
Sub-classing the Thread Class
Sub-classing the Thread class is not as popular because it is not as flexible as
implementing "Runnable" however it is very easy to create.
Implementing "Runnable" is more flexible because you can sub-class any class you
desire.
-
Objectives
- Create a thread by sub-classing the Thread class.
- See how a class constructors can be used to give a Thread a name.
-
ThreadsHelloWorldWaysThread.java.txt - Hello World example of sub-classing the "Thread" class.
Here is an example of the java console results:
Thread-0 - Hello World from a thread! (subclasses Thread)
Thread-1 - Hello World from a thread! (subclasses Thread)
ThreadHW1 - Hello World from a thread! (subclasses Thread)
ThreadOneLine1 - Hello World from a thread! (subclasses Thread)
ThreadAnonymousClass - Hello World from a thread! (anonymous class) (subclasses Thread)
- Right click on the link(s) above and open in a new window so we can do a
code-walkthrough.
- Building on the previous code-walkthroughs above we will just
discuss the new items.
- This class sub-classes the Thread object.
ex: public class ThreadsHelloWorldThread extends Thread
- When this class is executed by java.exe the "main" method will run
first.
- main() then does the following:
Thread.sleep()
Thread.sleep() causes the current running thread to sleep for a specified
time. After that time, the thread will continue to run when the processor
is available.
Thread.interrupt()
Thread.interrupt() is an indication to a thread, by another thread, that it
is being requested to do something else. It is up to the thread being
interrupted to decide what it will do, however, termination of the thread is
very common.
-
Objectives
- Understand how the Thread's isAlive() method works
- Learn how to interrupt a thread.
- See an example of how a thread can decide what to do when an interrupt
is received.
- Discuss how the main() thread can finish while the other threads
continue to run.
-
ThreadsHelloWorldInterruptSimple.java.txt - Hello World example of using the
Thread.interrupt() method.
Here is an example of the java console results:
main - Begin - Fri Jul 04 20:37:14 EDT 2008
main - before objThreadHW1.start() - objThreadHW1.isAlive() = false
main - before objThreadHW1.start() - objThreadHW1.isAlive() = true
main - Before 2 second sleep (Sleep #1) - Fri Jul 04 20:37:14 EDT 2008
ThreadHW1 - Start Time - Fri Jul 04 20:37:14 EDT 2008
main - After 2 second sleep (Sleep #1) - Fri Jul 04 20:37:16 EDT 2008
main - Before 4 second sleep (Sleep #2) - Fri Jul 04 20:37:16 EDT 2008
ThreadHW1 - Hello World #1 - Fri Jul 04 20:37:16 EDT 2008
ThreadHW2 - Start Time - Fri Jul 04 20:37:16 EDT 2008
ThreadHW1 - Hello World #2 - Fri Jul 04 20:37:18 EDT 2008
ThreadHW2 - Hello World #1 - Fri Jul 04 20:37:18 EDT 2008
ThreadHW1 - Hello World #3 - Fri Jul 04 20:37:20 EDT 2008
main - After 4 second sleep (Sleep #2) - Fri Jul 04 20:37:20 EDT 2008
main - Before objThreadHW1.interrupt() - objThreadHW1.isAlive() = true
ThreadHW1 - Interrupted Time - Fri Jul 04 20:37:20 EDT 2008
ThreadHW1 - Stop Time - Fri Jul 04 20:37:20 EDT 2008
main - After objThreadHW1.interrupt() - objThreadHW1.isAlive() = false
ThreadHW2 - Hello World #2 - Fri Jul 04 20:37:20 EDT 2008
ThreadHW2 - Interrupted Time - Fri Jul 04 20:37:20 EDT 2008
ThreadHW2 - I'm to busy having fun to break! - Fri Jul 04 20:37:20 EDT 2008
ThreadHW2 - Hello World #3 - Fri Jul 04 20:37:20 EDT 2008
main - After objThreadHW2.interrupt() - objThreadHW2.isAlive() = true
main - Finished - Fri Jul 04 20:37:20 EDT 2008
ThreadHW3 - Start Time - Fri Jul 04 20:37:20 EDT 2008
ThreadHW2 - Hello World #4 - Fri Jul 04 20:37:22 EDT 2008
ThreadHW3 - Hello World #1 - Fri Jul 04 20:37:22 EDT 2008
ThreadHW2 - Hello World #5 - Fri Jul 04 20:37:24 EDT 2008
ThreadHW2 - Stop Time - Fri Jul 04 20:37:24 EDT 2008
ThreadHW3 - Hello World #2 - Fri Jul 04 20:37:24 EDT 2008
ThreadHW3 - Hello World #3 - Fri Jul 04 20:37:26 EDT 2008
ThreadHW3 - Hello World #4 - Fri Jul 04 20:37:28 EDT 2008
ThreadHW3 - Hello World #5 - Fri Jul 04 20:37:30 EDT 2008
ThreadHW3 - Stop Time - Fri Jul 04 20:37:30 EDT 2008
- Right click on the link(s) above and open in a new window so we can do a
code-walkthrough.
- Building on the previous code-walkthroughs above we will just
discuss the new items.
- Look at the code and the java console output and notice the following:
- main Thread
- Notice how the other threads continue to execute while the main thread
is sleeping.
- Notice how the threads continue to execute even when the main thread had
finished with the message "main - Finished ..."
- Thread.sleep()
- Thread.sleep() puts the current thread to sleep. In this example
we have 4 threads: main, ThreadHW1, ThreadHW2, ThreadHW3.
- Each thread controls it's own execution.
- ThreadHW1
- isAlive() - For ThreadHW1, the thread's isAlive() method is false until
the thread's start() method is executed.
isAlive() later became false when the thread decided to finish when it was
interrupted.
- After HreadHW1 was interrupted it decided to break the
for loop and then finish executing.
- ThreadHW2
- When ThreadHW2 was interrupted it replied with "I'm to busy having fun to
break!". The tread decided to continue it's execution until it was
completely finished.
- Finished the code walkthrough.
Thread.interrupt() - busy thread supporting interrupt.
-
Objectives
- Discuss how a thread uses the method Thread.interrupted() to know that
it has been interrupted.
- See how the interrupt status is reset once a Thread checks to see if he
was interrupted.
- Discuss how a thread can decide what to do when it is interrupted.
-
ThreadsHelloWorldInterruptCheckSimple.java.txt - Hello World example of
a busy thread looking for an interrupt but completing part of a task prior
to stopping.
Here is an example of the java console results:
main - Begin - Fri Jul 04 22:01:11 EDT 2008
ThreadHW1 - Start Time - Fri Jul 04 22:01:11 EDT 2008
ThreadHW1 - Hello World #1 - Fri Jul 04 22:01:11 EDT 2008
ThreadHW1 - Hello World #2 - Fri Jul 04 22:01:12 EDT 2008
ThreadHW1 - Hello World #3 - Fri Jul 04 22:01:12 EDT 2008
ThreadHW1 - Hello World #4 - Fri Jul 04 22:01:12 EDT 2008
ThreadHW1 - Hello World #5 - Fri Jul 04 22:01:13 EDT 2008
main - before objThreadHW1.interrupt() - Fri Jul 04 22:01:13 EDT 2008
main - after objThreadHW1.interrupt() - Fri Jul 04 22:01:13 EDT 2008
main - Finished - Fri Jul 04 22:01:13 EDT 2008
ThreadHW1 - Interrupted Time, but I'm busy so wait! - Completed 5783479 loops - Fri Jul 04 22:01:13 EDT 2008
ThreadHW1 - Hmmmm, the interrupt was reset! Now Thread.interrupted() = false - 5783479 loops - Fri Jul 04 22:01:13 EDT 2008
ThreadHW1 - Hello World #6 - Fri Jul 04 22:01:13 EDT 2008
ThreadHW1 - thread not finished, but will exit here - Fri Jul 04 22:01:13 EDT 2008
ThreadHW1 - Stop Time - Completed 6000000 loops - Fri Jul 04 22:01:13 EDT 2008
- Right click on the link(s) above and open in a new window so we can do a
code-walkthrough.
- Building on the previous code-walkthroughs above we will just
discuss the new items.
- Description of the java app:
- This java app will create a thread and then 2 seconds later send an
interrupt to the thread.
- If the thread was never interrupted it would loop 100 times and within
those loops do some data crunching (1,000,000 loops at a time).
- While data crunching the thread will check to see if it has been
interrupted. If it has, it will finish the data crunching loop and
then exit.
- Thread.interrupted() -
- In the thread's run() method notice how the thread checks to see if it
was interrupted while it was data crunching inside of the 1,000,000 "for
loop".
ex: if (Thread.interrupted() ) {
- Look at the console results and notice that the tread was part way
through completing the 1,000,000 loops.
The tread wrote to the console it's loop count at that time.
- Look at the console results and notice that the interrupt status was
reset after the Thread checked the status.
ex: ThreadHW1 - Hmmmm, the interrupt was reset! Now Thread.interrupted() = false
...
- blnWasInterrupted was set to true so that the thread knows to later
break it's main loop because the thread interrupt status was reset when the
thread checked it.
- At a controlled exit point the thread decides to break out of the for
loop and exit.
ex:
if ( blnWasInterrupted ) {
System.out.println(strThreadName + " - thread not finished, but will exit here - " + (new Date()).toString());
break;
}
-
Finished the code walkthrough.
Thread.wait() & Thread.interrupt()
-
Objectives
- Learn how to put a thread into a wait status.
- See the use of synchronizing a code block.
-
ThreadsHelloWorldWaitInterruptSimple.java.txt - Hello World example of
a thread deciding it needs to wait on another tread to provide some data.
The thread providing the data then interrupts the thread so it can continue
processing.
Here is an example of the java console results:
main - Begin - Fri Jul 04 22:08:24 EDT 2008
main - before 2 second sleep - Fri Jul 04 22:08:24 EDT 2008
ThreadHW1 - Start Time - Fri Jul 04 22:08:24 EDT 2008
ThreadHW1 - Hello World #1 - Will need info soon! - Fri Jul 04 22:08:24 EDT 2008
ThreadHW1 - Hello World #2 - Will need info soon! - Fri Jul 04 22:08:24 EDT 2008
ThreadHW1 - Let's wait() - Fri Jul 04 22:08:24 EDT 2008
main - after 2 second sleep - Fri Jul 04 22:08:26 EDT 2008
main - objThreadHW1.interrupt() - Fri Jul 04 22:08:26 EDT 2008
ThreadHW1 - Interrupted Time - Fri Jul 04 22:08:26 EDT 2008
ThreadHW1 - Hello World #3 - Got it now! - Fri Jul 04 22:08:26 EDT 2008
ThreadHW1 - Hello World #4 - Got it now! - Fri Jul 04 22:08:26 EDT 2008
ThreadHW1 - Hello World #5 - Got it now! - Fri Jul 04 22:08:26 EDT 2008
ThreadHW1 - Stop Time - Fri Jul 04 22:08:26 EDT 2008
main - Finished - Fri Jul 04 22:08:26 EDT 2008
- Right click on the link(s) above and open in a new window so we can do a
code-walkthrough.
- Building on the previous code-walkthroughs above we will just
discuss the new items.
- The main thread of this java app creates a thread named "ThreadHW1" then
starts the thread.
The main thread then decides to sleep for 2 seconds.
- Meanwhile, while ThreadHW1 is looping it decides during the 3rd loop to
go into a wait() state because it wants to wait to get a message from the
main thread. getStrMsg() has been blank and now he wants to wait for
the message.
- 2 seconds after the main thread created ThreadHW1 it decides to put a
message into a String that "ThreadHW1" can access.
ex: objRunnable1.setStrMsg("Got it now! - ");.
- The main tread then interrupts ThreadHW1 so that it can get the message.
- Now when ThreadHW1 writes to the console the method getStrMsg() will
display the message that the main thread created.
- The code block in the thread needs to be synchronized before the wait() method is called
or the JVM will throw and "IllegalMonitorStateException" exception.
synchronized ( this ) {
this.wait(); //Thread wants to wait until main thread creates a message for him.
}
-
Finished the code walkthrough.
Thread.wait() & Thread.notify()
-
ThreadsHelloWorldWaitNotify.java.txt - Hello World example of
a thread deciding it needs to wait on another tread to provide some data.
The thread providing the data then notifies the thread so it can continue
processing.
Here is an example of the java console results:
main - Begin - Fri Jul 04 22:47:54 EDT 2008
main - before 2 second sleep - Fri Jul 04 22:47:54 EDT 2008
ThreadHW1 - Start Time - Fri Jul 04 22:47:54 EDT 2008
ThreadHW1 - Hello World #1 - Fri Jul 04 22:47:54 EDT 2008
ThreadHW1 - Hello World #2 - Fri Jul 04 22:47:54 EDT 2008
ThreadHW1 - Let's wait() - Fri Jul 04 22:47:54 EDT 2008
main - after 2 second sleep - Fri Jul 04 22:47:56 EDT 2008
main - Let's objRunnable1.notify(); - Fri Jul 04 22:47:56 EDT 2008
ThreadHW1 - Hello World #3 - Got it now! - Fri Jul 04 22:47:56 EDT 2008
ThreadHW1 - Hello World #4 - Got it now! - Fri Jul 04 22:47:56 EDT 2008
ThreadHW1 - Hello World #5 - Got it now! - Fri Jul 04 22:47:56 EDT 2008
ThreadHW1 - Stop Time - Fri Jul 04 22:47:56 EDT 2008
main - Finished - Fri Jul 04 22:47:56 EDT 2008
- Right click on the link(s) above and open in a new window so we can do a
code-walkthrough.
- Building on the previous code-walkthroughs above we will just
discuss the new items.
- This java app does the same thing as the previous one (ThreadsHelloWorldWaitInterruptSimple.java.txt).
- The new concept here is that you need to synchronize the code block that
notifies the thread or the JVM will throw an "IllegalMonitorStateException"
exception.
try {
System.out.println(strThreadName + " - Let's objRunnable1.notify(); - " + (new Date()).toString());
synchronized ( objRunnable1 ) {
objRunnable1.notify();
//objThreadHW1.notify(); //The tread does not have the monitor. Runnable does.
}
} catch (IllegalMonitorStateException e) {
System.out.println(strThreadName + " - Illegal Monitor State Exception (IllegalMonitorStateException) - you can't do that! - " + (new Date()).toString());
}
-
Finished the code walkthrough.
Thread.join()
Thread.join() allows the current thread to wait for the specified thread
(using <ThreadObjectName>.join()) to complete before the current thread
continues. Remember that timing is dependent on the OS.
-
ThreadsHelloWorldJoinSimple.java.txt - Hello World example of using the
Thread.join() method.
Here is an example of the java console results:
main - Begin - Fri Jul 04 23:09:51 EDT 2008
ThreadHW1 - Start Time - Fri Jul 04 23:09:51 EDT 2008
ThreadHW1 - Hello World #1 - Fri Jul 04 23:09:53 EDT 2008
ThreadHW1 - Hello World #2 - Fri Jul 04 23:09:55 EDT 2008
ThreadHW1 - Hello World #3 - Fri Jul 04 23:09:57 EDT 2008
ThreadHW1 - Hello World #4 - Fri Jul 04 23:09:59 EDT 2008
ThreadHW1 - Hello World #5 - Fri Jul 04 23:10:01 EDT 2008
ThreadHW1 - Stop Time - Fri Jul 04 23:10:01 EDT 2008
main - before objThreadHW2.start() Fri Jul 04 23:10:01 EDT 2008
From main(), Finished - Fri Jul 04 23:10:01 EDT 2008
ThreadHW2 - Start Time - Fri Jul 04 23:10:01 EDT 2008
ThreadHW2 - Hello World #1 - Fri Jul 04 23:10:03 EDT 2008
ThreadHW2 - Hello World #2 - Fri Jul 04 23:10:05 EDT 2008
ThreadHW2 - Hello World #3 - Fri Jul 04 23:10:07 EDT 2008
ThreadHW2 - Hello World #4 - Fri Jul 04 23:10:09 EDT 2008
ThreadHW2 - Hello World #5 - Fri Jul 04 23:10:11 EDT 2008
ThreadHW2 - Stop Time - Fri Jul 04 23:10:11 EDT 2008
- Right click on the link(s) above and open in a new window so we can
do a code-walkthrough.
- Building on the previous code-walkthroughs above we will just
discuss the new items.
- In the main() method the code below will make the main thread pause
until ThreadHW1 (objThreadHW1) completes.
objThreadHW1.start(); //Start this thread, then continue on.
objThreadHW1.join(); //Pauses the main()'s thread until objThreadHW1 completes.
-
Look at the java console results above and you will see that the main thread
outputs to the console right after the ThreadHW1 completes.
-
Also note that the main thread finishes right after it starts ThreadHW2.
ThreadHW2 which continues to execute until it finishes.
-
Finished the code walkthrough.
Synchronizing Threads
This example shows how you can synchronize threads so a thread will wait on
another thread to place data into an object before it retrieves that data.
-
Objectives
- Learn how to synchronize a method.
- Create a class that will wait & notify the proper threads to set and get
values between them.
-
ThreadsHelloWorldSyncSetGet_Run.java.txt - Run thread - java class that runs the app.
ThreadsHelloWorldSyncSetGet_Set.java.txt - Set thread - the java thread that sets the
data.
ThreadsHelloWorldSyncSetGet_Get.java.txt - Get thread - the java thread that gets the
data.
ThreadsHelloWorldSyncSetGet_HoldValue.java.txt - Hold Value class - holds the synchronized data.
Here is an example of the java console results:
main - Begin - Sat Jul 05 00:56:35 EDT 2008
ThreadSet - Start Time - Sat Jul 05 00:56:35 EDT 2008
ThreadSet - Sleep seconds = 1 - Sat Jul 05 00:56:35 EDT 2008
ThreadGet - Start Time - Sat Jul 05 00:56:35 EDT 2008
ThreadSet - Set value! - Hello World #1 - Sat Jul 05 00:56:36 EDT 2008
ThreadGet - Got it! - Hello World #1 - Sat Jul 05 00:56:36 EDT 2008
ThreadSet - Sleep seconds = 1 - Sat Jul 05 00:56:36 EDT 2008
ThreadSet - Set value! - Hello World #2 - Sat Jul 05 00:56:37 EDT 2008
ThreadGet - Got it! - Hello World #2 - Sat Jul 05 00:56:37 EDT 2008
ThreadSet - Sleep seconds = 3 - Sat Jul 05 00:56:37 EDT 2008
ThreadSet - Set value! - Hello World #3 - Sat Jul 05 00:56:40 EDT 2008
ThreadGet - Got it! - Hello World #3 - Sat Jul 05 00:56:40 EDT 2008
ThreadSet - Sleep seconds = 0 - Sat Jul 05 00:56:40 EDT 2008
ThreadSet - Set value! - Hello World #4 - Sat Jul 05 00:56:40 EDT 2008
ThreadGet - Got it! - Hello World #4 - Sat Jul 05 00:56:40 EDT 2008
ThreadSet - Sleep seconds = 2 - Sat Jul 05 00:56:40 EDT 2008
ThreadSet - Set value! - Hello World #5 - Sat Jul 05 00:56:42 EDT 2008
ThreadSet - Stop Time - Sat Jul 05 00:56:42 EDT 2008
ThreadGet - Got it! - Hello World #5 - Sat Jul 05 00:56:42 EDT 2008
ThreadGet - Stop Time - Sat Jul 05 00:56:42 EDT 2008
main - Finished - Sat Jul 05 00:56:42 EDT 2008
- Right click on the link(s) above and open in a new window so we can
do a code-walkthrough.
- Building on the previous code-walkthroughs above we will just
discuss the new items.
- Here is an overview of the code-walkthrough.
- The Run thread creates the HoldValue object which will hold the
messages exchanged between the Set thread and Get thread.
- This one HoldValue object is passed to the Set thread and Get thread
as the threads are instantiated so that they have access to the common
object that holds the messages.
- After the Run thread starts the Set thread and Get thread it
immediately does an objSetThread.join() so that it pauses until the Set
thread completes.
- The Set thread places a message in
the HoldValue object which then does a notifyAll() and waits for the
Get thread to get the message because it was awaken by the Set thread's
notifyAll().
- The Get thread is interrupted by the notifyAll() so that it can get
the message in the HoldValue object which then does a notifyAll() and
waits for the Set thread to put another message because it was awaken by
the Get thread's notifyAll().
- This handshaking between the Set & Get threads repeats until the Set thread is finished putting messages.
- When the Set thread completes, the Run thread tells the HoldValue object that there will be no more messages
calling the method "objHoldValue.setBlnFinished(true)" which will then interrupts the Get
thread which is currently in a wait() state inside the HoldValue object.
In the HoldValue object the interrupt exception is caught and because
isBlnFinished() is true a new InterruptedException() is thrown.
This is caught in the Get thread which then decides to exit.
- Now all the threads have finished.
- To understand the way the Set thread, Get thread and the HoldValue
object passes messages we will discuss the key concepts in the Set thread,
the Get thread and then the HoldValue object.
- Key concepts in the Set thread:
- Notice that there is a for loop that will loop 5 times
which is designed to place 5 messages into the HoldValue object.
- The Set object will sleep based on a random generate value from
0 thru 3.
- Next the Set thread will place a message into the HoldValue
object by calling: objHoldValue.setSyncValue( strMsg )
- objHoldValue.setSyncValue( strMsg ) will the cause the Set
thread to wait until the Get thread gets the message.
- Key concepts in the Get thread:
- The while loop causes the Get thread to call objHoldValue.getSyncValue() until objHoldValue.isBlnFinished() is
true.
- objHoldValue.getSyncValue() will get the message then notify
the Set thread that it can put another message.
- Key concepts in the HoldValue thead:
- The getSyncValue() is synchronized so that only one thread at a time
can run the method.
ex: public synchronized String getSyncValue() throws
InterruptedException {
- The setSyncValue() is synchronized so that only one thread at a time
can run the method.
ex: public synchronized void setSyncValue(String strPutValue) {
- Key concepts in the setSyncValue() method of the HoldValue object:
- If blnValueReadyForGet is true then the Set thread will wait()
until the Get thread notifies Set to continue.
- When the Set thread continues it puts a new message, does
blnValueReadyForGet = true and then does a
notifyAll() which will interrupt the Get thread.
- Key concepts in the getSyncValue() method of the HoldValue object:
- If "blnValueReadyForGet == false" then the Get thread will
wait() for the Set thread to call notifyAll.
- When interrupted, If isBlnFinished() is false the Get thread is
interrupted and it will call blnValueReadyForGet = false;,
notifyAll(); which will wake up the Set thread and then returns the
message to the Get thread.
Else ("blnValueReadyForGet == true) the tread will throw the
exception InterruptedException().
- This handshaking, using wait() & notifyAll(), continues until all of the
messages have been communicated between the Set and Get threads.
- Finished the code walkthrough.
Lab #1
- Using the example above for "Synchronizing Threads" create a set of
classes that will do the following:
- Have a "set thread" that sets the message in the "HoldValue" class
as in the example.
- Have two "get threads" that get the message from the "HoldValue"
class.
- The "set thread" must allow both "get threads" to get the messages
before it continues.
- When the "set thread" has finished and both "get threads" have
received the messages the have the "get threads" finish.
Optional Lab #2
- Using the example above for "Synchronizing Threads" create a set of
classes that will do the following:
- Create a Cat thread object that will randomly move every 1 to 5
seconds. Output to the system console that the Cat moved.
- When the Cat thread moves the Dog thread will bark. Output to
the system console that the Dog barked.
- After 15 seconds the Dog will chase and the Cat will then run away.
Output to the system console a "Dog Chase" and/or a "Cat Run" type
messages.
Topics for future Java Thread Tutorials: (Hello World types)
- setPriority & yeild()
- Thread Groups
- java.util.Timer
- java.swing.Timer
- Deadlock example & fix.
- Applet examples
Swing examples
- Executor - java.util.concurrent.ScheduledThreadPoolExecutor
- Locks - java.util.concurrent.locks.ReentrantLock - 1.5 replaces
synchronized key word.