DOC PREVIEW
UMD CMSC 132 - Multithreading in Java

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

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 28 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 28 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 28 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 28 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 28 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 28 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 28 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 15Alternative (Not Recommended)Why not recommended?Threads – Thread StatesSlide 19Threads – SchedulingJava Thread ExampleJava Thread Example – OutputDaemon ThreadsMight not see different interleavingsData RacesWhy volatileThread Scheduling ObservationsUsing SynchronizationMultithreading in JavaNelson Padua-PerezBill PughDepartment 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…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…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”Web Server uses threads to handle …Multiple simultaneous web browser requestsMotivation for MultithreadingCaptures logical structure of problemMay have concurrent interacting componentsCan handle each component using separate threadSimplifies programming for problemExampleMultiple simultaneous web browser requests…Handled faster by multiple web serversMotivation for MultithreadingBetter utilize hardware resourcesWhen a thread is delayed, compute other threadsGiven extra hardware, compute threads in parallelReduce overall execution timeExampleMultithreading 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 JavaYou have to specify the work you want the thread to doDefine a class that implements the Runnable interfacepublic interface Runnable { public void run(); }Put the work in the run methodCreate an instance of the worker class and create a thread to run itor hand the worker instance to an executorThread Classpublic class Thread { public Thread(Runnable R); // Thread  R.run() public Thread(Runnable R, String name);public void start(); // begin thread execution ...}More Thread Class Methodspublic class Thread { …public String getName(); public void interrupt(); public boolean isAlive(); public void join(); public void setDaemon(boolean on); public void setName(String name); public void setPriority(int level);public static Thread currentThread(); public static void sleep(long milliseconds); public static void yield();}Creating Threads in JavaRunnable 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 parallelAlternative (Not Recommended)Directly extend Thread classpublic class MyT extends Thread { public void run() { … // work for thread }}MyT t = new MyT(); // create threadt.start(); // begin running threadWhy not recommended?Not a big problem for getting startedbut a bad habit for industrial strength developmentThe methods of the worker class and the Thread class get all tangled upMakes it hard to migrate to Thread Pools and other more efficient approachesThreads – Thread StatesJava thread can be in one of these statesNew – thread allocated & waiting for start()Runnable – thread can executeBlocked – thread waiting for event (I/O, etc.)Terminated – thread finishedTransitions between states caused byInvoking methods in class Threadstart(), yield(), sleep()Other (external) eventsScheduler, I/O, returning from run()…Threads – Thread StatesState diagramrunnablenewterminatedblockednewstartterminateIO, sleep, join,request lockIO complete, sleep expired,join complete,acquire lockThreads – SchedulingSchedulerDetermines which runnable threads to runCan be based on thread priorityPart of OS or Java Virtual Machine (JVM) Many computers can run multiple threads simultaneously (or nearly so)Java Thread Examplepublic class ThreadExample implements Runnable { public void run() { for (int i = 0; i < 3; i++) System.out.println(i); } public static void main(String[] args) { new Thread(new ThreadExample()).start();new Thread( new ThreadExample()).start(); System.out.println("Done"); }}Java Thread Example – OutputPossible outputs0,1,2,0,1,2,Done // thread 1, thread 2, main()0,1,2,Done,0,1,2 // thread 1, main(), thread 2Done,0,1,2,0,1,2 // main(), thread 1, thread 20,0,1,1,2,Done,2 // main() & threads interleavedthread 1: println 0, println 1, println 2main (): thread 1, thread 2, println Donethread 2: println 0, println 1, println 2Daemon ThreadsWhy doesn’t the program quit as soon as Done is printed?Java threads typesUserDaemonProvide general services Typically never terminateCall setDaemon() before start()Program terminationIf all non-daemon threads terminate, JVM shuts downMight not see different interleavingsThe threads in that example are too


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?