DOC PREVIEW
Penn CIT 594 - Threads and Multithreading

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

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

Unformatted text preview:

Threads and MultithreadingMultiprocessingMultithreadingWhy multithreading?ThreadsSleepingStates of a ThreadState transitionsTwo ways of creating ThreadsExtending ThreadImplementing RunnableStarting a ThreadExtending Thread: summaryImplementing Runnable: summaryTwo kinds of ThreadsThings a Thread can doAnimation requires two ThreadsHow to animateThings a Thread should NOT doHow to stop another ThreadHow to pause another ThreadA problemTools for a solutionwait(), notify(), notifyAll()The EndJan 14, 2019Threads and Multithreading2MultiprocessingModern operating systems are multiprocessingAppear to do more than one thing at a timeThree general approaches:Cooperative multiprocessingPreemptive multiprocessingReally having multiple processors3MultithreadingMultithreading programs appear to do more than one thing at a timeSame ideas as multiprocessing, but within a single programMore efficient than multiprocessingJava tries to hide the underlying multiprocessing implementation4Why multithreading?Allows you to do more than one thing at oncePlay music on your computer’s CD player,Download several files in the background,while you are writing a letterMultithreading is essential for animationOne thread does the animationAnother thread responds to user inputs5ThreadsA Thread is a single flow of controlWhen you step through a program, you are following a ThreadYour previous programs all had one ThreadA Thread is an Object you can create and control6SleepingEvery program uses at least one ThreadThread.sleep(int milliseconds);A millisecond is 1/1000 of a secondtry { Thread.sleep(1000); }catch (InterruptedException e) { }sleep only works for the current Thread7States of a ThreadA Thread can be in one of four states:Ready: all set to runRunning: actually doing somethingWai ting, or blocked: needs somethingDead: will never do anything againState names vary across textbooksYou have some control, but the Java scheduler has more8State transitionsreadywaitingrunning deadstart9Two ways of creating ThreadsThe easy way:Extend the Thread class:class Animation extends Thread {…}And override public void run()You can only extend one class, so if your class already extends some other class, you can’t do thisThe more general way:Implement the Runnable interface:class Animation implements Runnable {…}Override public void run( )Create a new Thread with this class as a parameterMost of the time, you need to do things the second way10Extending Threadclass Animation extends Thread { public void run( ) { code for this thread } Anything else you want in this class}Animation anim = new Animation( );A newly created Thread is in the Ready stateTo start the anim Thread running, call anim.start( );start( ) is a request to the scheduler to run the Thread --it may not happen right awayThe Thread should eventually enter the Running state11Implementing Runnableclass Animation implements Runnable {…}The Runnable interface requires run( )This is the “main” method of your new Thread Animation anim = new Animation( ); Thread myThread = new Thread(anim);To start the Thread running, call myThread.start( );You do not write the start() method—it’s provided by JavaAs always, start( ) is a request to the scheduler to run the Thread--it may not happen right away12Starting a ThreadEvery Thread has a start( ) methodDo not write or override start( ) You call start( ) to request a Thread to runThe scheduler then (eventually) calls run( )You must supply public void run( )This is where you put the code that the Thread is going to run13Extending Thread: summaryclass Animation extends Thread { public void run( ) { while (okToRun) { ... } }}Animation anim = new Animation( );anim.start( );14Implementing Runnable: summaryclass Animation extends Applet implements Runnable { public void run( ) { while (okToRun) { ... } }}Animation anim = new Animation( );Thread myThread = new Thread(anim);myThread.start( );15Two kinds of ThreadsThere are two kinds of Threads in Java:Nondaemon threadsThese are “independent” threads, which run until they reach a stopping point (for example, the end of your main method)Whenever you start a program, you get one nondaemon threadWhen you create a GUI, you get another nondaemon threadDaemon threadsThese are threads which die when all nondaemon threads finishThe Java VM exits when only daemon threads are still runningThere are methods setDaemon(boolean) and boolean isDaemon()The System.exit(int) method kills all threads16Things a Thread can doThread.sleep(milliseconds)yield( )Thread me = currentThread( );int myPriority = me.getPriority( );me.setPriority(NORM_PRIORITY);if (otherThread.isAlive( )) { … }join(otherThread);17Animation requires two ThreadsSuppose you set up Buttons and attach Listeners to those buttons...…then your code goes into a loop doing the animation……who’s listening?Not this code; it’s busy doing the animationsleep(ms) doesn’t help!18How to animateCreate your buttons and attach listeners in your first (original) ThreadCreate a second Thread to run the animationStart the animationThe original Thread is free to listen to the buttonsHowever,Whenever you have a GUI, Java automatically creates a second (nondaemon) Thread for youYou only have to do this yourself for more complex programs19Things a Thread should NOT doThe Thread controls its own destinyDeprecated methods:myThread.stop( )myThread.suspend( )myThread.resume( )Outside control turned out to be a Bad IdeaDon’t do this!20How to stop another ThreadDon’t use the deprecated methods!Instead, put a request where the other Thread can find itboolean okToRun = true;animation.start( );public void run( ) { while (okToRun) {...main loop...}21How to pause another ThreadDon’t use the deprecated methods!Instead, put a request where the other Thread can find itboolean paused = false;public void run( ) { while (okToRun) { while (paused) { try { Thread.sleep(100); } catch (InterruptedException e) { } } ...main loop... }}22A problemWhat gets printed as the value of k?This is a trivial example of what is, in general, a very difficult problemint k = 0;Thread


View Full Document

Penn CIT 594 - Threads and Multithreading

Documents in this Course
Trees

Trees

17 pages

Searching

Searching

24 pages

Pruning

Pruning

11 pages

Arrays

Arrays

17 pages

Stacks

Stacks

30 pages

Recursion

Recursion

25 pages

Hashing

Hashing

24 pages

Recursion

Recursion

24 pages

Graphs

Graphs

25 pages

Storage

Storage

37 pages

Trees

Trees

21 pages

Arrays

Arrays

24 pages

Hashing

Hashing

24 pages

Recursion

Recursion

25 pages

Graphs

Graphs

23 pages

Graphs

Graphs

25 pages

Stacks

Stacks

25 pages

Recursion

Recursion

25 pages

Quicksort

Quicksort

21 pages

Quicksort

Quicksort

21 pages

Graphs

Graphs

25 pages

Recursion

Recursion

25 pages

Searching

Searching

24 pages

Counting

Counting

20 pages

HTML

HTML

18 pages

Recursion

Recursion

24 pages

Pruning

Pruning

11 pages

Graphs

Graphs

25 pages

Load more
Download Threads and Multithreading
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 Multithreading 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 Multithreading 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?