Title: Threads in Java
1Threads in Java
- Shon Vick
- CMSC 291
- Advanced Java Topics
2What Is a Thread?
- Familiar with writing sequential programs
- At any given time during the runtime of the
program, there is a single point of execution. - The program has a beginning, an execution
sequence, and an end - So do threads except that they run within a
program
3Threads run within Programs
- A thread itself is not a program it cannot run
on its own. - A Thread runs within a program and can execute a
set of instructions completely independent of
other threads in the same process
4Why are threads useful?
- Can be doing multiple things (multiple execution
paths) at once. - Example Browser
- Loading an applet
- Scrolling down a page
- Printing
5Threads
- Lightweight process
- A thread is similar to a real process in that a
thread and a running program are threads of
execution - A thread takes advantage of the resources
allocated for that program instead of having to
allocate those resources again
6Threads
- A thread has its own stack and program counter
for example.) - The code running within the thread works only
within the context implied by the stack and PC so
also called a execution context
7A Thread Example
// This class extends the Thread class class
MyThread extends Thread // Override the
Thread's class run() method public void run()
System.out.println("Hello there, from "
getName())
From Berg Chapter 11 see references
8An example
public class ExtendThr static public void
main(String s) MyThread Thread_a,
Thread_b // Define the threads Thread_a
new MyThread() // Create MyThread object
Thread_b new MyThread() // Create another
MyThread object Thread_a.start() // Start
the run() method in thread a
Thread_b.start() // Start the run() method in
thread b
From Berg Chapter 11 see references
9Creating and Starting a Thread
public class Echo extends Thread private
String word private int waitTime // in
millisecs public Echo(String word, int
waitTime) this.word word this.waitTime
waitTime Modified From Arnold and
Gosling Chapter 9 see references
10Creating and Starting a Thread
public void run( ) try while (true)
System.out.print(word )
sleep(waitTime)
catch (InterruptedException e) return()
// end the thread
11Creating and Starting a Thread
public static void main(String args) Echo
e1 new Echo(Foo, 200) Echo e2
new Echo(Bar, 200)
12An Alternate Mechanism
// Class the implements the Runnable
interface class MyThread2 implements Runnable
public void run() System.out.println("Hi
there, from "
Thread.currentThread().getName())
From Berg Chapter 11 see references
13An Alternate Mechanism
public class RunnableThr static public void
main(String s) MyThread2 work2do //
Object that has work to be done Thread
a_thread, b_thread // A thread object on which
to run the work // Create the MyThread2
object work2do new MyThread2()
14An Alternate Mechanism
// Create a thread with the MyThread2 object as
its target a_thread new Thread(work2do)
b_thread new Thread(work2do) // Start
the thread which will call run() in the target
a_thread.start() b_thread.start()
15A Sample Use
- Suppose that we have a server that has many
clients connected to it - We would like to start a new thread for each
client connection - What happens if we do not?
- Our server waits for a connection with accept and
when a connection is made a new thread to handle
that connection is created - Example from Berg Chapter 4 see references
16A Server Example
public class MultiThreadedServer public
static void main( String args ) throws
Exception // create a server side
socket - same as before ServerSocket server
new ServerSocket( 9999 )
Need a server socket to listen for connections
17A Server Example
block
while( true ) Socket socket
server.accept() new ThreadedSocket( socket
).start()
Start the thread
Pass the socket along
Create a Thread object
18A Server Example
class ThreadedSocket extends Thread
ThreadedSocket( Socket socket ) this.socket
socket //
Remember the socket
19A Server Example
public void run() try // create the
Objects for the Client
ObjectOutputStream output
new ObjectOutputStream( socket.getOutputStream()
) output.writeObject(
stuffForClient) socket.close()
catch( Exception e ) e.printStackTrace()
20Sharing Data
- In our previous example the socket class was
never shared by more than one thread because
every accept inside the while results in a new
thread - What if that were not the case?
- Suppose we had the notion of an account that
would be shared across threads
21Synchronized Methods
public class Account private double
balance public Account(double initial)
balance initial public synchronized
double getBalance() return balance
public synchronized double deposit(double amt)
balance amt
One at a time
22Synchronized Methods
- With synchronized two or more running threads are
guaranteed not to interfere with one another - If there are read and write methods they should
be synchronized - Another reason for accessors
- Static methods may also be locked class wide
lock - Why doesnt the constructor need to be
synchronized?
23Synchronized Statements
- The Synchronized statement enables you to execute
synchronized code that locks an object without
invoking a Synchronized method - The Synchronized statement has two parts
- An object to be locked
- A statement to execute when the lock is obtained
24Synchronized Statements
// in some class public static void abs(int
values) synchronized (values) for (int
i 0 i lt values.length I) if
(valuesi lt 0 ) valuesi - valuesi
25From Last Time?
- Whats a thread?
- How is it different from a process?
- What are the two ways to create and use one in
Java? - How are the two ways different?
- What sample application did we examine?
- How did it work?
26Thread States Horstmann
- New
- Before start()
- Runnable
- After start but may not actually yet be running
- How the thread actually starts running is OS
dependent - Underlying thread package is implementation
specific
27An (Incomplete) Finite State Diagram
28Blocked Threads
- Sleep method called
- Waiting for I/O
- Thread calls wait method
- Thread tries to lock an object currently locked
by another thread - The deprecated suspend method is invoked
29Example
class MyThread extends Thread //
public void run ( ) try while
(!isInterrupted() ) doSomething()
sleep(5)
Could catch InterruptedExection
30Moving out of a blocked State
- Sleep time expires
- I/O operation finishes
- If a thread called wait and another thread calls
notify or notify all - Another thread relinquishes a lock
- Resume
31Joining a Thread Berg
- Provides a way for one thread to wait for another
to complete - If there is a direct dependency on the execution
of one thread before another can continue then a
thread join can be used to wait for that
particular thread - A thread waits for its target thread to die
32Joining a ThreadBerg
public class JoinThr static public void
main(String s) MyThread1 Thread_a //
Define a Thread MyThread2 Thread_b //
Define another Thread Thread_a new
MyThread1() // Create the Thread object
Thread_b new MyThread2(Thread_a) // Create the
Thread object // Start the threads
System.out.println("Starting the threads...")
Thread_a.start() Thread_b.start()
33Joining a ThreadBerg
// Thread class that just prints a message 5
times class MyThread1 extends Thread public
void run() System.out.println(getName() "
is running...") for (int i0 ilt4 i)
try // Sleep a bit sleep(500)
catch (InterruptedException e)
System.out.println("Hello there, from "
getName())
34Joining a ThreadBerg
class MyThread2 extends Thread private
Thread wait4me // Thread to wait for //
Constructor MyThread2(Thread target)
super() wait4me target
35Joining a ThreadBerg
public void run() System.out.println(getName
() " is waiting for " wait4me.getName()
"...") try // wait for target thread to
finish wait4me.join() catch
(InterruptedException e) //
36Joining a ThreadBerg
System.out.println(wait4me.getName() " has
finished...") // Print message 4 times
for (int i0 ilt4 i) try // Sleep a
bit sleep(500) catch
(InterruptedException e)
System.out.println("Hello there, from "
getName())
37Run Berg
Hello There, From Thread-4 Hello There, From
Thread-4 Hello There, From Thread-4 Hello There,
From Thread-4 Thread-4 has finished.. Hello
There, From Thread-5 Hello There, From
Thread-5 Hello There, From Thread-5 Hello There,
From Thread-5
38Daemon Threads Berg
- A daemon thread is like a demon process
- Stops execution when all other non daemon threads
die - Provides a handy way to have threads read in the
background that go away when their service is no
longer needed
39Normal Thread Berg
class normal extends Thread public void
run() for (int i0 ilt5 i) try
// Sleep for a bit sleep(500)
catch (InterruptedException e)
System.out.println("I am a normal thread")
System.out.println("The normal thread is
exiting")
40Daemon Thread Berg
class daemon extends Thread public daemon()
setDaemon(true) public void
run() for (int i0 ilt10 i) try
// Sleep for a bit sleep(500)
catch (InterruptedException e)
System.out.println("I am a daemon thread")
Note
41Driver Berg
public class DaemonThr static public void
main(String s) normal Thread_a //
Define some Threads daemon Thread_b //
Create the threads Thread_a new normal()
Thread_b new daemon()
System.out.println("Starting the threads...")
Thread_a.start() // Start the Thread
Thread_b.start() // Start the Thread
42Output Berg
Starting the threads.. Thread-4 I am a normal
thread Thread-5 I am a daemon thread Thread-4 I
am a normal thread Thread-5 I am a daemon
thread Thread-4 I am a normal thread Thread-5 I
am a daemon thread The normal thread is exiting
43The synchronized Keyword
- Implements a monitor
- Only one thread allowed access to the object at a
time - Multiple threads in the same code of different
objects allowed - Only one thread in any of the code of a single
object - Example Producer Consumer Example from Gittleman
and Tutorial
44Synchronize and Mutexs Holub
- Monitors can be used to implement
mutual-exclusion semaphores (mutex) - Use a static Object on which to synchronize
- Only one thread allowed access to the critical
section of code at a time - Object independent -- when a thread is executing
critical code of one object, no thread can
execute that code even on another object - Example Updating a static counter
45class Notifying_queue private static Object
lock new Object() private static int count
0 private static final queue_size 10
private Object queue new Object queue_size
private int head 0 private int
tail 0 public void synchronized
enqueue( Object item ) incrementCount()
queuehead queue_size item
this.notify() public Object
synchronized dequeue( ) try while(
head tail ) this.wait() catch(
InterruptedException e ) return null //
wait abandoned incrementCount()
return queuetail queue_size
private void incrementCount()
synchronized(lock) count
46More Synchronization Mechanisms Arnold
- The synchronized locking mechanism works for
keeping threads from interfering with each other
but sometimes a way to communicate amongst
threads is needed - The wait() method lets one thread wait until some
condition occurs - The notifyAll() and notify() methods tell waiting
threads that something has occurred that might
satisy that condition
47Standard Pattern
synchronized void doWhenCondition() while
(!condition) wait() // do what needs to be
done while condition is true
synchronized void changeCondition() //
change some condition notifyAll( )
48Waiting and Notification
- Multiple Threads could be waiting on some object
- Notify viz NotifyAll
49Selected References
- Advanced Techniques for Java Developers,Berg
Fritzinger, Chapter 11 Wiley, 1999 - The online Java Tutorial http//java.sun.com/docs/
books/tutorial/essential/threads/ - The Java Programming Language , K.Arnold and J.
Gosling , Addison-Wesley , 1996 Chapter 9
50References
- Advanced Techniques for Java Developers,Berg
Fritzinger, Chapter 11 Wiley, 1999 Berg - Java Tutorial Tutorial
- Online
- Hardcopy
- The Java Programming Language , K.Arnold and J.
Gosling , Addison-Wesley , 1996 Chapter 9
Arnold - Objects to Components With the Java Platform,
Gittleman, Scott/Jones Publishing, 2000
Gittleman
51References
- Core Java, Volume II, Advanced Features,
Horstmann and Cornell, Prentice Hall, 2000
Horstmann - Taming Java Threads, Allen Holub , Apress, 2000
Holub