DOC PREVIEW
UMD CMSC 433 - Threads and Synchronization

This preview shows page 1-2-3-24-25-26 out of 26 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 26 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 26 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 26 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 26 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 26 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 26 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 26 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

1CMSC 433 – Programming LanguageTechnologies and ParadigmsSpring 2004Threads and Synchronization(thanks to Doug Lea for some slides)2Administrivia• Project 4 posted later today– Due April 14• Midterms handed back now– Please pick yours up• Project 3 regrades– Please see message on newsgroup23Tools Available for Project 4• FindBugs– Finds some common wait/notify problems– Not guaranteed to be correct• Dynamic lock checking tool checkSync– Every shared object must be guarded by a lock– Again, not guaranteed to be correct4Overview• What are threads?– Concept– Basic Java mechanisms• Thread concerns– Safety and Liveness– Use of synchronization and signalling• Threading design patterns35Computation AbstractionsCPU 1 CPU 2p3p1 p2 p4t1t2t1t2t3t1t4t5A computerProcesses(e.g., JVM’s)Threads6Processes vs. Threadsint x;foo() {…x…}int x;foo() {…x…}int x;foo() { …x…}foo() { …x…}Processes do notshare dataThreads share datawithin a process47So, 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)8Why 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 OS59Why Not Multiple Threads?• Complexity:– Dealing with safety, liveness, composition• Overhead– Higher resource usage• We’ll compare threads to their alternatives abit later …10Programming 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 specification611Java 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.12Java 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() methodreturns713Java Threads: Creationapp threadmainstartrunnew14Running 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 seconds815Example: 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);}16Making 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); }}917Making It Threaded (2)while (true) { System.out.print("Alarm> "); // read user input String line = b.readLine(); // creates AlarmThread to wait timeout secs Thread t = parseInput(line); // start alarm thread if (t != null) t.start();}18Alternative: 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)1019Thread 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); }}20Change is in parseInput• Old parseInput does– return new AlarmThread(m,t);• New parseInput does– return new Thread(new AlarmRunnable(m,t));• Code in while loop doesn’t change1121Notes: 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 class22Thread 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?1223Thread 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 time24Scheduling Example (1)CPU 1CPU 2p1p2p1p2One process per CPUp2 threads:p1 threads:1325Scheduling Example (2)CPU 1CPU 2p1p2p1p2Threads shared between CPU’sp2 threads:p1 threads:26Scheduling 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 threads1427Thread 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– Not all JVMs use preemptive scheduling, so a threadstuck in a loop may never yield by itself. Therefore,put yield() into loops• Threads are de-scheduled whenever they block(e.g., on a lock or on I/O) or go to sleep28Thread Lifecycle• While a thread executes, it goes through anumber of different phases– New:


View Full Document

UMD CMSC 433 - Threads and Synchronization

Documents in this Course
Trace 1

Trace 1

62 pages

Reflection

Reflection

137 pages

Testing

Testing

25 pages

Paradigms

Paradigms

10 pages

Testing

Testing

17 pages

Java RMI

Java RMI

17 pages

Java RMI

Java RMI

17 pages

Java RMI

Java RMI

17 pages

Trace 1

Trace 1

46 pages

Jini

Jini

4 pages

Final

Final

15 pages

Java RMI

Java RMI

13 pages

Testing

Testing

16 pages

Load more
Download Threads and Synchronization
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Threads and Synchronization and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Threads and Synchronization 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?