Definitions A glossary Threads From Volume II Copyright 1998-2002 Delroy A. Brinkerhoff. All Rights Reserved. Threads Slide 1 of 30 PMultitasking: (concurrent ramming, multiramming) the illusion of running more than one job at time by allowing jobs to share the CPU (time slicing) PContet switch: switching the CPU between jobs; requires saving one job s state while restoring another job s state PPreemptive multitasking: Operating system schedules the contet switch based on a maimum time slice < Uni, all varieties (at the ess level) < Windows 95/98/NT PCooperative multitasking: task must relinquish the CPU < Windows 3.1 < Solaris green threads Threads Slide 2 of 30 Process aka heavy weight ess Process Creation Programs become esses PProgram whose eecution has started & not yet terminated parent child POne main per ess (with one caveat) Pfork( ) duplicates a ess (data and instructions) PProcesses do not directly share data < Identical esses have distinct data < Communication, data sharing, and synchronization are OS services PCalled heavy weight because contet switch is etensive fork esses created from 1 ram do not share data. forking a ess dubplicates data; data still not shared Threads Slide 3 of 30 Threads Slide 4 of 30 Thread aka light weight ess or thread of control Thread Eample Concurrent function/method eecution P Threads originate from a single ram < A thread is a concurrent flow of eecution of a task in a ram < They are the concurrent eecution of functions or methods within the ram < Do not duplicate any code or data < Threads share global data (instance variables in Java ) < Thread contet switch time is less than for esses because there is less state to save and restore do to the shared data < A single ess may be multithreaded P Two types of threads < System level implemented in the OS (kernel) < Application level implemented in the application (language) but still requires OS support main() threadstart(fill) threadstart(empty) fill()... empty()... ess ess empty fill data threads empty fill data Threads Slide 5 of 30 Threads Slide 6 of 30
Thread States Similar to Uni ess states P new created but not scheduled to run P ready scheduled and capable of running P running: has the CPU runnable P blocked: waiting for a service (e.g., an I/O operation) to finish P asleep: called the sleep() method; sleeps for set time P suspend: called the suspend() method; must resume() P waiting: P dead: called the wait() method; must notify() or notifyall() run() ends or stop() called; cannot restart Threads Slide 7 of 30 Thread State Changes Dynamic Thread behavior running waiting suspend asleep blocked new start( ) ready run( ) completes or stop( )* dead * deprecated at 1.2 Threads Slide 8 of 30 Basic Thread Methods Defined in java.lang.thread Petends Thread < Thread( ) constructor < override the run( ) method Pimplements Runnable < Thread(Runnable object) create and use with Thread object < implement the run( ) method Pvoid run( ) concurrent eecution (called by scheduler) Pvoid start( ) schedules thread, scheduler calls run( ) Pvoid join( ) t.join( ) waits for thread t to finish < join(long ms)as above but continues after ms milliseconds Pvoid sleep(n) pauses calling thread for m milliseconds < sleep(m, n) sleeps thread for m millisecons + n nanoseconds Threads Slide 9 of 30 Thread Methods Continued P void yield( ) voluntarily relinquishes the CPU P void wait( ) thread relinquishes all locks and self-blocks P void notify( ) restarts a thread blocked on a wait() P void notifyall( ) restarts all threads blocked with a wait() P void destroy( ) terminates a thread without cleanup P boolean isalive( ) true if the thread is started & not terminated P void interrupt( ) interrupts this thread P boolean isinterrupted( ) is specified thread interrupted P boolean interrupted( ) static: was current thread interrupted P InteruptedEception thrown by sleep( ) and wait( ) Threads Slide 10 of 30 Scheduling Threads To Run Concurrency in Java rams PYou can call a thread s run method, but that does not run it concurrently PA dead thread may not be restarted or recycled < But you can call a dead thread object s other methods public class MyThread etends Thread... Thread T = new MyThread ( ); T.start( ); // inherited from Thread Threads Slide 11 of 30 Terminating Threads When Threads quit // do something useful boolean done = false; while (! done) if (some condition is met) done = true; // do something useful Threads Slide 12 of 30
Multitasking Concepts A task may be either a thread or a ess P Critical resource a limited (finite number or amount) commodity that a task needs to complete its task P Critical section a code segment in a task that uses a critical resource P Mutual eclusion a protocol to limit the number of tasks in a critical section < when no task is in a critical section, a requesting task is not delayed < when two tasks compete for a critical section, the selection cannot be postponed indefinitely < no task can prevent another from entering its critical section indefinitely P Deadlock 2 or more tasks each have a mutual eclusion lock on a resource needed by another Threads Slide 13 of 30 Multitasking Concepts Continued P Starvation a task is never allowed access to a critical resource; it is never allowed to run to completion P Atomic test and set an uninterleavable instruction that tests and sets the value of a variable P Fairness contention for a critical resource is resolved < weak fairness: if a task continuously makes a request, it is eventually satisfied < strong fairness: if a task makes a request infinitely often, it is eventually satisfied < linear waiting: if a task makes a request, it is granted before any other task is granted the same request more than once < FIFO waiting: if a task makes a request, it will be granted before that of a task making a later request Threads Slide 14 of 30 Competing Tasks Mutual eclusion eample Mutual Eclusion In Java synchronized methods (Hoare s Monitors) mutual eclusion widgets = N + widgets inventroy update task if (inuse == false) inuse = true else block widgets 10 inuse = false critical resource atomic test and set instruction widgets = widgets - 1 POS task Threads Slide 15 of 30 P synchronized (keyword) at most one Thread allowed in a synchronized method (others are blocked) synchronized public void Insert( ) // critical section PEach class and each object with one or more synchronized methods has one lock and one queue < Static methods use the class s lock < Non-static methods use the per object lock < A thread entering a synchronized method acquires the object s lock and other threads entering any of the object s synchronized methods are suspended and placed on the wait-queue Threads Slide 16 of 30 Waiting Threads Two places-- two selection algorithms Simple Mutual Eclusion Serializing access (compare with slide 15) T 9 T 8 queue (FIFO) T 3 T 7 T 1 T 2 T 6 wait( ) T 5 T 0 T 4 notifyall( ) synchronized Monitor-- synchronized method Threads Slide 17 of 30 public class Inventory private int widgets; // critical resource synchronized public void update(int N) widgets += N; synchronized public void sell( ) widgets -= 1; // class Inventory Threads Slide 18 of 30
Fine-grained Mutual Eclusion (synchronized blocks) P Create an object and use it s lock to provide mutual eclusion on a block of code P You may use the lock object s methods and data class Lock... Lock BlockLock = new Lock( ); void public somemethod( )... synchronized (BlockLock) // critical section... // stylistically preferred void public mymethod( )... synchronized(this) // critical section... Threads Slide 19 of 30 The Producer/Consumer Problem (the bounded buffer problem) P Producer threads write data to a finite Buffer object P Consumer threads read from the Buffer object P Buffer variables that must be protected < counter how may elements in Buffer < front insert location in Buffer < back remove location in Buffer P Producers must increment counter and front P Consumer must decrement counter and increment back P Two threads cannot change a variable at the same time P One thread cannot change a variable while another thread tests its value Threads Slide 20 of 30 Producer/Consumer Illustrated Buffer State Diagram OMT state diagram from the dynamic model producer1 producer2 producer3 counter == 4 back Inserting store / insert [counter = bufsize] eit / stored store / insert [counter < bufsize] Buffer Empty Partially Filled Filled Consumer front Compare with PipedInputStream Buffer object & PipedOutputStream Threads Slide 21 of 30 [counter > 0] retrieve / remove Retrieving eit / retrieved [counter = 0] retrieve / remove Threads Slide 22 of 30 Implementing Mutual Eclusion Java synchronization features (See Buffer.java) Referencing A Common Object See Producer.java synchronized public void insert while (counter == bufsize) wait( ); put stuff in the Buffer counter++; notifyall( ); synchronized public int remove while (counter == 0) wait( ); take stuff out of the Buffer counter--; notifyall( ); public class Producer etends Thread int ID; // used to identify a Producer Buffer StoreBuffer; // shared by all Producers & Consumer public Producer(int id, Buffer Buff) ID = id; StoreBuffer = Buff; while (true) int rand = (int)(4000 * Math.random( )); try Thread.sleep(rand); // simulates work catch (InterruptedEception e) StoreBuffer.Insert(ID, rand); // end class Producer Threads Slide 23 of 30 Threads Slide 24 of 30
Referencing A Common Object See Consumer.java public class Consumer etends Thread Buffer StoreBuffer; public Consumer(Buffer Buff) StoreBuffer = Buff; while (true) int rand = (int)(2000 * Math.random()); try Thread.sleep(rand); // simulates work catch (InterruptedEception e) StoreBuffer.Remove( ); // class Consumer Coordinating Threads See Driver.java public class Driver public static void main(string args[ ]) Buffer buff = new Buffer(); Producer P1 = new Producer(1, buff); Producer P2 = new Producer(2, buff); Producer P3 = new Producer(3, buff); Consumer C = new Consumer(buff); P1.start(); P2.start(); P3.start(); C.start(); // class Driver Threads Slide 25 of 30 Threads Slide 26 of 30 Synchronization Summary Monitors and Java s synchronized Methods Pwait < Can only be called within a synchronized method < Thread blocks and is placed in the object s queue Pnotify / notifyall < Can only be called within a synchronized method < Unblocks a / some Thread(s) waiting for an object s state to change PSynchronization rules < If 2 or more Threads modify an object (i.e., change any instance variables), make the methods that effect the changes synchronized < If a Thread must wait to change an object, it should wait inside the object by calling a synchronized method and then by calling wait < Whenever a thread changes an object, it should call notify or notifyall Threads Slide 27 of 30 The Runnable Interface Multithreading Applets (see DClock.java, Train.java, & ThreadAppProto.java) P Using the Runnable interface < implement Runnable < Override run( ) method < Instantiate a Thread and pass it a reference to the main object public class DClock etends Applet implements Runnable while (true) repaint( ); try Thread.sleep(1000); catch (InterruptedEception e) public void start() if (AppletThread == null) AppletThread = new Thread(this); AppletThread.start( ); Threads Slide 28 of 30 Runnable Interface Eample From class Token (Stratego project) Thread Priorities High priority Threads run before low priority Threads public class Token implements Runnable public void epose(space location) display = true; this.location = location; Thread timer = new Thread(this); timer.start( ); try Thread.sleep(10000); catch (InterruptedEception ie) System.err.println("Timer error"); display = false; location.repaint( ); Threads Slide 29 of 30 P Three defined priorities < MIN_PRIORITY 1 < NORM_PRIORITY 5 < MAX_PRIORITY 10 P Altering thread priority < getpriority( ) < setpriority( ) < Attempting to set a priority that is out of range will result in an IllegalArgumentEception P How priority effects scheduling is implementation dependent Threads Slide 30 of 30