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 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)ApproachMultiple processing units (multiprocessor)Computer works on several tasks in parallelPerformance can be improved4096 processorCray X132 processorPentium XeonDual-core AMDAthlon X2Perform Multiple Tasks Using…ProcessDefinition – executable program loaded in memoryHas 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 ofinstructionsShares address space with other threadsHas own execution contextProgram counter, call stack (local variables)Communicate via shared access to dataMultiple threads in process execute same programAlso known as “lightweight process”Web Server usesthreads to handle …Multiple simultaneousweb browser requestsMotivation for MultithreadingCaptures logical structure of problemMay have concurrent interacting componentsCan handle each component using separate threadSimplifies programming for problemExampleMultiple simultaneousweb browser requests…Handled faster bymultiple web serversMotivation for MultithreadingBetter utilize hardware resourcesWhen a thread is delayed, compute other threadsGiven extra hardware, compute threads in parallelReduce overall execution timeExampleMultithreading OverviewMotivation & backgroundThreadsCreating 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 thethread to doDefine a class that implements the Runnableinterfacepublic interface Runnable { public void run();}Put the work in the run methodCreate an instance of the worker class andcreate 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 theThread class get all tangled upMakes it hard to migrate to Thread Pools andother 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 threadssimultaneously (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 isprinted?Java threads typesUserDaemonProvide general servicesTypically 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 shortEach started thread will probably completebefore the next thread startsLet’s make more threads that run longerData Racespublic class DataRace implements Runnable { static volatile int x; public void run() { for (int i = 0; i < 10000; i++) { x++; x--; } } public static void main(String[] args) throws Exception { Thread [] threads = new Thread[100]; for (int i = 0; i < threads.length; i++) threads[i] = new Thread(new DataRace()); for (int i = 0; i < threads.length; i++) threads[i].start(); for (int i = 0; i < threads.length; i++)


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?