Title: Multithreading
1Multithreading
2Overview
- Class Thread
- Thread states
- Thread priorities and scheduling
- Synchronization
- Producer/Consumer relationships
- Daemon threads
- Runnable Interface
- Thread Groups
3Multithreading
- Concurrently running code
- Threads are concurrently running portions of the
same program - Multitasking is concurrently running programs on
a single user system - Multiprogramming is concurrently running programs
on a multiuser system - Multiprocessing is multiple CPUs
4Platform dependence
- Solaris Java is preemptive
- Windows 32-bit (95, 98, an NT) is time sliced
- Other platforms may have other methodologies
- Highly dependent on the operating system for
exactly how multithreading is implemented
5Class Thread
Thread() Thread(String name) -- thread name
Thread-n void run() -- actual working code
written by programmer void start() -- called to
start a thread static void sleep(long
millis) static boolean interrupted() -- returns
interrupted state boolean isAlive() -- started
but not completed setName(String s), String
getName() static Thread currentThread() --
reference to currently executing
6Thread States
Born
7Thread Priorities
- By default all threads are given
Thread.NORM_PRIORITY (5) - Thread.MIN_PRIORITY (1)
- Thread.MAX_PRIORITY (10)
- setPriority, getPriority
- Higher priority threads are run to completion
before lower priority ones - Could lead to starvation (indefinite
postponement)
8Thread Scheduling
- Thread executes until
- it dies
- it becomes blocked for I/O
- it calls sleep
- it calls wait (notify, notifyAll)
- it calls yield
- it is preempted by a higher priority
- its quantum (time slice) expires
9Thread example
// Show multiple threads printing at different
intervals. public class ThreadTester public
static void main( String args )
PrintThread thread1, thread2, thread3, thread4
thread1 new PrintThread( "thread1" )
thread2 new PrintThread( "thread2" )
thread3 new PrintThread( "thread3" )
thread4 new PrintThread( "thread4" )
10Thread example
System.err.println( "\nStarting threads"
) thread1.start()
thread2.start() thread3.start()
thread4.start() System.err.println(
"Threads started\n" )
11Thread example
public class PrintThread extends Thread
private int sleepTime // PrintThread
constructor assigns name to thread // by
calling Thread constructor public PrintThread(
String name ) super( name ) //
sleep between 0 and 5 seconds sleepTime
(int) ( Math.random() 5000 )
System.err.println( "Name " getName()
" sleep " sleepTime )
12Thread example
// execute the thread public void run()
// put thread to sleep for a random
interval try System.err.println(
getName() " going to sleep" )
Thread.sleep( sleepTime ) catch (
InterruptedException exception )
System.err.println( exception.toString() )
// print thread name
System.err.println( getName() " done sleeping"
)
13Thread example
Name thread1 sleep 1686 Name thread2
sleep 2867 Name thread3 sleep 1923 Name
thread4 sleep 838 Starting threads Threads
started thread1 going to sleep thread2 going to
sleep thread3 going to sleep thread4 going to
sleep thread4 done sleeping thread1 done
sleeping thread3 done sleeping thread2 done
sleeping
Name thread1 sleep 1904 Name thread2
sleep 4388 Name thread3 sleep 1700 Name
thread4 sleep 4868 Starting threads Threads
started thread2 going to sleep thread3 going to
sleep thread4 going to sleep thread1 going to
sleep thread3 done sleeping thread1 done
sleeping thread2 done sleeping thread4 done
sleeping
14Synchronization
- A method with the modifier synchronized
- Locks the object using the method
- All other synchronized methods must wait
- May issue the wait method to allow others access
- Use the notify or notifyAll method to allow
waiting threads access - Can also synchronized blocks of code
15Producer/Consumer relationship
- Shared memory (could be disk)
- One thread is putting information in -- i.e.,
producing - One thread is taking information out -- i.e.,
consuming - Must have synchronization to get reliable results
16Synchronization example
// Show multiple threads modifying shared
object. public class SharedCell public
static void main( String args )
HoldIntegerSynchronized h new
HoldIntegerSynchronized() ProduceInteger p
new ProduceInteger( h ) ConsumeInteger c
new ConsumeInteger( h ) p.start()
c.start()
17Synchronization example
// Definition of threaded class
ProduceInteger public class ProduceInteger
extends Thread private HoldIntegerSynchronize
d pHold public ProduceInteger(
HoldIntegerSynchronized h ) super(
"ProduceInteger" ) pHold h
18Synchronization example
public void run() for ( int count
1 count lt 10 count ) // sleep for
a random interval try
Thread.sleep( (int) ( Math.random() 3000 ) )
catch( InterruptedException e )
System.err.println( e.toString()
) pHold.setSharedInt( count
) System.err.println( getName()
" finished producing values"
"\nTerminating " getName() )
19Synchronization example
// Definition of threaded class
ConsumeInteger public class ConsumeInteger
extends Thread private HoldIntegerSynchronize
d cHold public ConsumeInteger(
HoldIntegerSynchronized h ) super(
"ConsumeInteger" ) cHold h
20Synchronization example
public void run() int val, sum 0
do // sleep for a random interval
try Thread.sleep( (int) (
Math.random() 3000 ) )
catch( InterruptedException e )
System.err.println( e.toString() )
val cHold.getSharedInt() sum
val while ( val ! 10 )
System.err.println( getName() "
retrieved values totaling " sum
"\nTerminating " getName() )
21Synchronization example
// Definition of class HoldIntegerSynchronized
that // uses thread synchronization to ensure
that both // threads access sharedInt at the
proper times. public class HoldIntegerSynchronized
private int sharedInt -1 private
boolean writeable true // condition variable
22Synchronization example
public synchronized void setSharedInt( int val
) while ( !writeable ) // not the
producer's turn try
wait() catch (
InterruptedException e )
e.printStackTrace()
System.err.println( Thread.currentThread().getName
() " setting sharedInt to " val )
sharedInt val writeable false
notify() // tell a waiting thread to become
ready
23Synchronization example
public synchronized int getSharedInt()
while ( writeable ) // not the consumer's
turn try wait()
catch ( InterruptedException e )
e.printStackTrace()
writeable true notify() // tell a
waiting thread to become ready
System.err.println( Thread.currentThread().getName
() " retrieving sharedInt value "
sharedInt ) return sharedInt
24Synchronization example
ConsumeInteger retrieving sharedInt value
1 ProduceInteger setting sharedInt to
2 ConsumeInteger retrieving sharedInt value
2 ProduceInteger setting sharedInt to
3 ConsumeInteger retrieving sharedInt value
3 ProduceInteger setting sharedInt to
4 ConsumeInteger retrieving sharedInt value
4 ProduceInteger setting sharedInt to
5 ConsumeInteger retrieving sharedInt value
5 ProduceInteger setting sharedInt to
6 ConsumeInteger retrieving sharedInt value
6 ProduceInteger setting sharedInt to
7 ConsumeInteger retrieving sharedInt value
7 ProduceInteger setting sharedInt to
8 ConsumeInteger retrieving sharedInt value
8 ProduceInteger setting sharedInt to
9 ConsumeInteger retrieving sharedInt value
9 ProduceInteger setting sharedInt to
10 ProduceInteger finished producing
values Terminating ProduceInteger ConsumeInteger
retrieving sharedInt value 10 ConsumeInteger
retrieved values totaling 55 Terminating
ConsumeInteger
25Miscellaneous
- Producer/Consumer can be more efficient with a
Circular Buffer - Daemon Threads -- setDaemon and isDaemon
- run in background
- do not prevent the program from terminating
- must be set before the start method called
26Runnable Interface
- Implement the Runnable interface rather than
extend Thread - Need to implement the run method
- Allows for inheritance as well as threads
- Pass the class that implements Runnable to the
Thread constructor - new Thread(Runnable r)
27Runnable Example
import java.io. public class NameUsingThread
implements Runnable private int time
private Thread thread public NameUsingThread(Str
ing n, int t) timet thread new
Thread(this,n) thread.start() public
void run() for (int i1ilt5i)
System.out.println(thread.getName() " " i)
try Thread.sleep(time)
catch (InterruptedException e) return
//for //run
28Runnable Example
public static void main(String argv)
NameUsingThread bonnie new NameUsingThread("Bonn
ie",1000) NameUsingThread clyde new
NameUsingThread("Clyde",700) for (int
i1ilt5i) System.out.println(Thread.cu
rrentThread().getName() " " i) try
Thread.sleep(1100) catch
(InterruptedException e) return //for
//main //class
29Runnable Example
30Thread Groups
- Class ThreadGroup
- Can deal with all Threads in a group as one set
-- e.g. interrupt them all
ThreadGroup(String name) ThreadGroup(ThreadGroup
parentGroup, String name) Thread(ThreadGroup tg,
String name) Thread(ThreadGroup tg, Runnable
runnableObject) Thread(ThreadGroup tg, Runnable
ro, String name)
31ThreadGroup methods
int activeCount() int enumerate() -- copy into
an array of Threads or ThreadGroups int
getMaxPriority(), setMaxPriority(in pri) String
getName() ThreadGroup getParent() boolean
parentOf(ThreadGroup tg)
32Summary
- Class Thread
- Thread states
- Thread priorities and scheduling
- Synchronization
- Producer/Consumer relationships
- Daemon threads
- Runnable Interface
- Thread Groups