DOC PREVIEW
UMD CMSC 132 - Multithreading in Java

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

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 27 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 27 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 27 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 27 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 27 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 27 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 27 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

Multithreading in JavaProblemMultitasking (Time-Sharing)Multitasking Can Aid PerformanceMultiprocessing (Multithreading)Perform Multiple Tasks Using…Slide 7Motivation for MultithreadingSlide 9Multithreading OverviewProgramming with ThreadsCreating Threads in JavaThread ClassMore Thread Class MethodsSlide 15Slide 16Slide 17Threads – Thread StatesSlide 19Daemon ThreadsThreads – SchedulingThreads – Non-preemptive SchedulingThreads – Preemptive SchedulingJava Thread ExampleJava Thread Example – OutputData RacesThread Scheduling ObservationsMultithreading in JavaNelson Padua-PerezChau-Wen TsengDepartment of Computer ScienceUniversity of Maryland, College ParkProblemMultiple tasks for computerDraw & display images on screenCheck keyboard & mouse inputSend & receive data on networkRead & write files to diskPerform useful computation (editor, browser, game)How does computer do everything at once?MultitaskingMultiprocessingMultitasking (Time-Sharing)ApproachComputer does some work on a taskComputer then quickly switch to next taskTasks managed by operating system (scheduler)Computer seems to work on tasks concurrentlyCan improve performance by reducing waitingMultitasking Can Aid PerformanceSingle taskTwo tasksMultiprocessing (Multithreading)Approach Multiple processing units (multiprocessor)Computer works on several tasks in parallelPerformance can be improved4096 processor Cray X132 processor Pentium XeonDual-core AMD Athlon X2Perform Multiple Tasks Using…1. ProcessDefinition – executable program loaded in memory Has own address spaceVariables & data structures (in memory)Each process may execute a different programCommunicate via operating system, files, networkMay contain multiple threadsPerform Multiple Tasks Using…2. ThreadDefinition – sequentially executed stream of instructionsShares address space with other threadsHas own execution context Program counter, call stack (local variables)Communicate via shared access to dataMultiple threads in process execute same program Also known as “lightweight process”Motivation for Multithreading1. Captures logical structure of problemMay have concurrent interacting componentsCan handle each component using separate threadSimplifies programming for problemExampleWeb Server uses threads to handle …Multiple simultaneous web browser requestsMotivation for Multithreading2. Better utilize hardware resourcesWhen a thread is delayed, compute other threadsGiven extra hardware, compute threads in parallelReduce overall execution timeExampleMultiple simultaneous web browser requests…Handled faster by multiple web serversMultithreading OverviewMotivation & background ThreadsCreating Java threadsThread statesSchedulingSynchronizationData racesLocksWait / NotifyProgramming with ThreadsConcurrent programmingWriting programs divided into independent tasksTasks may be executed in parallel on multiprocessorsMultithreadingExecuting program with multiple threads in parallelSpecial form of multiprocessingCreating Threads in JavaTwo approachesThread classpublic class Thread extends Object { … }Runnable interfacepublic interface Runnable { public void run(); // work  thread}Thread Classpublic class Thread extends Object implements Runnable { public Thread(); public Thread(String name); // Thread name public Thread(Runnable R); // Thread  R.run() public Thread(Runnable R, String name); public void run(); // if no R, work for thread public void start(); // begin thread execution ...}More Thread Class Methodspublic class Thread extends Object { … public static Thread currentThread() public String getName() public void interrupt() public boolean isAlive() public void join() public void setDaemon() public void setName() public void setPriority() public static void sleep() public static void yield()}Creating Threads in Java1. Thread classExtend Thread class and override the run methodExamplepublic class MyT extends Thread { public void run() { … // work for thread }}MyT T = new MyT () ; // create threadT.start(); // begin running thread… // thread executing in parallelCreating Threads in Java2. Runnable interfaceCreate object implementing Runnable interfacePass it to Thread object via Thread constructorExamplepublic class MyT implements Runnable { public void run() { … // work for thread }}Thread T = new Thread(new MyT); // create threadT.start(); // begin running thread… // thread executing in parallelCreating Threads in JavaNoteThread starts executing only if start() is calledRunnable is interfaceSo it can be multiply inherited Required for multithreading in appletsThreads – Thread StatesJava thread can be in one of these statesNew – thread allocated & waiting for start()Runnable – thread can begin executionRunning – thread currently executingBlocked – thread waiting for event (I/O, etc.)Dead – thread finishedTransitions between states caused byInvoking methods in class Threadnew(), start(), yield(), sleep(), wait(), notify()…Other (external) eventsScheduler, I/O, returning from run()…Threads – Thread StatesState diagramrunnableschedulernewdeadrunning blockednewstartterminateIO, sleep,wait, joinyield,time slicenotify, notifyAll,IO complete, sleep expired,join completeDaemon ThreadsJava threads typesUserDaemonProvide general services Typically never terminateCall setDaemon() before start()Program termination1. All user threads finish2. Daemon threads are terminated by JVM3. Main program finishesThreads – SchedulingSchedulerDetermines which runnable threads to runCan be based on thread priorityPart of OS or Java Virtual Machine (JVM) Scheduling policyNonpreemptive (cooperative) schedulingPreemptive schedulingThreads – Non-preemptive SchedulingThreads continue execution until Thread terminatesExecutes instruction causing wait (e.g., IO)Thread volunteering to stop (invoking yield or sleep)Threads – Preemptive SchedulingThreads continue execution untilSame reasons as non-preemptive schedulingPreempted by schedulerJava Thread Examplepublic class ThreadExample extends Thread { public void run() { for (int i = 0; i < 3; i++) { try { sleep((int)(Math.random() * 5000)); // 5 secs } catch (InterruptedException e) { } System.out.println(i); } } public static void main(String[] args) { new ThreadExample().start(); new ThreadExample().start(); System.out.println("Done"); }}Java Thread Example –


View Full Document

UMD CMSC 132 - Multithreading in Java

Documents in this Course
Notes

Notes

8 pages

Recursion

Recursion

12 pages

Sorting

Sorting

31 pages

HTML

HTML

7 pages

Trees

Trees

19 pages

HTML

HTML

18 pages

Trees

Trees

19 pages

Honors

Honors

19 pages

Lecture 1

Lecture 1

11 pages

Quiz #3

Quiz #3

2 pages

Hashing

Hashing

21 pages

Load more
Download Multithreading in Java
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 Multithreading in Java 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 Multithreading in Java 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?