CMSC 433 – Programming LanguageTechnologies and ParadigmsFall 2006Threads and SynchronizationNovember 7th, 2006(thanks to Doug Lea for some slides)2Overview• What are threads?– Concept– Basic Java mechanisms• Thread concerns– Safety and Liveness– Use of synchronization and signalling• Threading design patterns3Computation Abstractionsp3p1 p2 p4t1t2t1t2t3t1t4t5A computerProcesses(e.g., JVM’s)ThreadsCPU 1CPU 24Processes vs. Threadsint x;foo() {…x…}int x;foo() {…x…}int x;foo() { …x…}foo() { …x…}Processes do notshare dataThreads share datawithin a process5So, What Is a Thread?• Conceptually: it is a parallel computationoccurring within a process• Implementation view: it’s a programcounter and a stack. The heap and staticarea are shared among all threads• All programs have at least one thread(main)6Why Multiple Threads?• Performance:– Parallelism on multiprocessors– Concurrency of computation and I/O• Can easily express some programming paradigms– Event processing– Simulations• Keep computations separate, as in an OS– Java OS7Why Not Multiple Threads?• Complexity:– Dealing with safety, liveness, composition• Overhead– Higher resource usage• We’ll compare threads to their alternatives abit later …8Programming Threads• Threads are available in many languages– C, C++, Objective Caml, Java, SmallTalk …• In many languages (e.g., C and C++),threads are a platform specific add-on– Not part of the language specification• Part of the Java language specification9Java Threads• Every application has at least one thread– The “main” thread, started by the JVM to runthe application’s main() method• The code executed by main() can createother threads– Explicitly, using the Thread class– Implicitly, by calling libraries that createthreads as a consequence• RMI, AWT/Swing, Applets, etc.10Java Threads: Creation• To explicitly create a thread– Instantiate a Thread object• An object of class Thread or a subclass of Thread– Invoke the object’s start() method• This will start executing the Thread’s run() methodconcurrently with the current thread– Thread terminates when its run() methodreturns11Java Threads: Creationapp threadmainstartrunnew12Running Example: Alarms• Goal: let us set alarms that will be triggeredin the future– Input: Time t (seconds) and message m– Result: We’ll see m printed after t seconds13Example: Synchronous alarmswhile (true) { System.out.print("Alarm> "); // read user input String line = b.readLine(); parseInput(line); // sets timeout // wait (in secs) try { Thread.sleep(timeout * 1000); } catch (InterruptedException e) { } System.out.println("("+timeout+") "+msg);}14Making It Threaded (1)public class AlarmThread extends Thread { private String msg = null; private int timeout = 0; public AlarmThread(String msg, int time) { this.msg = msg; this.timeout = time; } public void run() { try { Thread.sleep(timeout * 1000); } catch (InterruptedException e) { } System.out.println("("+timeout+") "+msg); }}15Making It Threaded (2)while (true) { System.out.print("Alarm> "); // read user input String line = b.readLine(); parseInput(line); if (m != null) { // start alarm thread Thread t = new AlarmThread(m,tm); t.start(); }}16Alternative: The Runnable Interface• Extending Thread prohibits a different parent• Instead implement Runnable– Declares that the class has a void run() method• Construct a Thread from the Runnable– Constructor Thread(Runnable target)– Constructor Thread(Runnable target, String name)17Thread Example Revisitedpublic class AlarmRunnable implements Runnable { private String msg = null; private int timeout = 0; public AlarmRunnable(String msg, int time) { this.msg = msg; this.timeout = time; } public void run() { try { Thread.sleep(timeout * 1000); } catch (InterruptedException e) { } System.out.println("("+timeout+") "+msg); }}18Thread Example Revisited (2)while (true) { System.out.print("Alarm> "); // read user input String line = b.readLine(); parseInput(line); if (m != null) { // start alarm thread Thread t = new Thread( new AlarmRunnable(m,tm)); t.start(); }}19Notes: Passing Parameters• run() doesn’t take parameters• We “pass parameters” to the new thread bystoring them as private fields– In the extended class– Or the Runnable object– Example: the time to wait and the message toprint in the AlarmThread class20Thread Scheduling• Once a new thread is created, how does itinteract with existing threads?• This is a question of scheduling:– Given N processors and M threads, whichthread(s) should be run at any given time?21Thread Scheduling• OS schedules a single-threaded process on asingle processor• Multithreaded process scheduling:– One thread per processor• Effectively splits a process across CPU’s• Exploits hardware-level concurrency– Many threads per processor• Need to share CPU in slices of time22Scheduling Example (1)CPU 1CPU 2p1p2p1p2One process per CPUp2 threads:p1 threads:23Scheduling Example (2)CPU 1CPU 2p1p2p1p2Threads shared between CPU’sp2 threads:p1 threads:24Scheduling Consequences• Concurrency– Different threads from the same application canbe running at the same time on differentprocessors• Interleaving– Threads can be pre-empted at any time inorder to schedule other threads25Thread Scheduling• When multiple threads share a CPU, must decide:– When the current thread should stop running– What thread to run next• A thread can voluntarily yield() the CPU– Call to yield may be ignored; don’t depend on it• Preemptive schedulers can de-schedule the currentthread at any time– Almost all JVMs use preemptive scheduling, but a few(embedded) JVM’s do not, so a thread stuck in a loopmay never yield by itself. Therefore, put yield() intoloops• Threads are de-scheduled whenever they block(e.g., on a lock or on I/O) or go to sleep26Thread Lifecycle• While a thread executes, it goes through anumber of different phases– New: created but not yet started– Runnable: is running, or can run on a free CPU– Blocked: waiting for I/O or on a lock– Sleeping: paused for a user-specified interval– Terminated: completed27Which Thread to Run Next?• The scheduler looks at all of the runnable threads,including threads that were unblocked because– A lock
View Full Document