CMSC 330: Organization of Programming Languages Multithreaded Programming in Java CMSC 330 2 Multiprocessors •! Description –! Multiple processing units (multiprocessor) –! From single microprocessor to large compute clusters –! Can perform multiple tasks in parallel simultaneously 106K processor IBM BlueGene/L 32 processor Pentium Xeon Dual-core AMD Athlon X2 CMSC 330 3 Computation Abstractions CPU 1 CPU 2 p3 p1 p2 p4 t1 t2 t1 t2 t3 t1 t4 t5 A computer Processes (e.g., JVM’s) Threads CMSC 330 4 Processes vs. Threads int x; foo() { …x… } int x; foo() { …x… } int x; foo() { …x… } foo() { …x… } Processes do not share data Threads share data within a processCMSC 330 5 So, What Is a Thread? •! Conceptually –! Parallel computation occurring within a process •! Implementation view –! Program counter and stack –! Heap and static area shared among all threads •! All programs have at least one thread (main) CMSC 330 6 Implementation View •! Per-thread stack and instruction pointer –! Saved in memory when thread suspended –! Put in hardware esp/eip when thread resumes eip eip eip esp esp esp CMSC 330 7 Tradeoffs •! Threads can increase performance –! Parallelism on multiprocessors –! Concurrency of computation and I/O •! Natural fit for some programming patterns –! Event processing –! Simulations •! But increased complexity –! Need to worry about safety, liveness, composition •! And higher resource usage CMSC 330 8 Programming Threads •! Threads are available in many languages –! C, C++, OCaml, Java, Ruby, … •! In many languages (e.g., C and C++), threads are a platform specific add-on –! Not part of the language specification –! Implemented as code libraries (e.g., pthreads) •! They're part of the Java language specificationCMSC 330 9 Java Threads •! Every application has at least one thread –! The “main” thread, started by the JVM to run the application’s main() method •! main() can create other threads –! Explicitly, using the Thread class –! Implicitly, by calling libraries that create threads as a consequence •! RMI, AWT/Swing, Applets, etc. CMSC 330 10 Thread Creation execution (time) main thread thread starts thread starts thread ends thread join CMSC 330 11 Thread Creation in Java •! 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() method concurrently with the current thread –! Thread terminates when its run() method returns CMSC 330 12 Running Example: Alarms •! Goal: let's set alarms which will be triggered in the future –! Input: time t (seconds) and message m –! Result: we’ll see m printed after t secondsCMSC 330 13 Example: Synchronous alarms while (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); } CMSC 330 14 Making 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); } } CMSC 330 15 Making 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(); } } CMSC 330 16 Alternative: 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)CMSC 330 17 Thread Example Revisited public 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); } } CMSC 330 18 Thread 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(); } } CMSC 330 19 Notes: Passing Parameters •! run() doesn’t take parameters •! We “pass parameters” to the new thread by storing them as private fields –! In the extended class –! Or the Runnable object –! Example: the time to wait and the message to print in the AlarmThread class CMSC 330 20 Concurrency •! A concurrent program is one that has multiple threads that may be active at the same time –! Might run on one CPU •! The CPU alternates between running different threads •! The scheduler takes care of the details –! Switching between threads might happen at any time –! Might run in parallel on a multiprocessor machine •! One with more than one CPU •! May have multiple threads per CPU •! Multiprocessor machines are becoming more common –! Multi-CPU machines aren't that expensive any more –! Dual-core CPUs are available nowCMSC 330 21 Scheduling Example (1) CPU 1 CPU 2 p1 p2 p1 p2 One process per CPU p2 threads: p1 threads: CMSC 330 22 Scheduling Example (2) CPU 1 CPU 2 p1 p2 p1 p2 Threads shared between CPU’s p2 threads: p1 threads: CMSC 330 23 Concurrency and Shared Data •! Concurrency is easy if threads don’t interact –! Each thread does its own thing, ignoring other threads –! Typically, however, threads must communicate •! In Java, communication via shared data –! Static and heap data can be accessed by all threads –! Called shared memory concurrency •! Potential pitfalls –! Different threads may access the heap simultaneously –! But the scheduler might interleave threads arbitrarily –! Problems can occur if we’re not careful. CMSC 330 24 Data Race Example
View Full Document