Threads and MultithreadingMultiprocessingMultithreadingWhy multithreading?ThreadsSleepingStates of a ThreadState transitionsTwo ways of creating ThreadsExtending ThreadImplementing RunnableStarting a ThreadExtending Thread: summaryImplementing Runnable: summaryThings a Thread can doAnimation requires two ThreadsHow to animateThings a Thread should NOT doHow to control another ThreadA problemTools for a solutionThe EndJan 14, 2019Threads and Multithreading2MultiprocessingModern operating systems are multiprocessingAppear to do more than one thing at a timeThree general approaches:Cooperative multiprocessingPreemptive multiprocessingReally having multiple processors3MultithreadingMultithreading programs appear to do more than one thing at a timeSame ideas as multiprocessing, but within a single programMore efficient than multiprocessingJava tries to hide the underlying multiprocessing implementation4Why multithreading?Allows you to do more than one thing at oncePlay music on your computer’s CD player,Download several files in the background,while you are writing a letterMultithreading is essential for animationOne thread does the animationAnother thread responds to user inputs5ThreadsA Thread is a single flow of controlWhen you step through a program, you are following a ThreadYour previous programs all had one ThreadA Thread is an Object you can create and control6SleepingEvery program uses at least one ThreadThread.sleep(int milliseconds);A millisecond is 1/1000 of a secondtry { Thread.sleep(1000); }catch (InterruptedException e) { }sleep only works for the current Thread7States of a ThreadA Thread can be in one of four states:Ready: all set to runRunning: actually doing somethingWai ting, or blocked: needs somethingDead: will never do anything againState names vary across textbooksYou have some control, but the Java scheduler has more8State transitionsreadywaitingrunning deadstart9Two ways of creating ThreadsYou can extend the Thread class:class Animation extends Thread {…}Limiting, since you can only extend one classOr you can implement the Runnable interface:class Animation implements Runnable {…}requires public void run( )I recommend the second for most programs10Extending Threadclass 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 stateTo start the anim Thread running, call anim.start( );start( ) is a request to the scheduler to run the Thread --it may not happen right awayThe Thread should eventually enter the Running state11Implementing Runnableclass 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 JavaAs always, start( ) is a request to the scheduler to run the Thread--it may not happen right away12Starting a ThreadEvery Thread has a start( ) methodDo not write or override start( ) You call start( ) to request a Thread to runThe 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( );15Things a Thread can doThread.sleep(milliseconds)yield( )Thread me = currentThread( );int myPriority = me.getPriority( );me.setPriority(NORM_PRIORITY);if (otherThread.isAlive( )) { … }join(otherThread);16Animation requires two ThreadsSuppose 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 animationsleep(ms) doesn’t help!17How to animateCreate your buttons and attach listeners in your first (original) ThreadCreate a second Thread to run the animationStart the animationThe original Thread is free to listen to the buttonsHowever,Whenever you have a GUI, Java automatically creates a second Thread for youYou only have to do this yourself for more complex programs18Things a Thread should NOT doThe Thread controls its own destinyDeprecated methods:myThread.stop( )myThread.suspend( )myThread.resume( )Outside control turned out to be a Bad IdeaDon’t do this!19How to control another ThreadDon’t use the deprecated methods!Instead, put a request where the other Thread can find itboolean okToRun = true;animation.start( );public void run( ) { while (controller.okToRun) {…}20A problemWhat gets printed as the value of k?This is a trivial example of what is, in general, a very difficult problemint k = 0;Thread #1: k = k + 1;Thread #2: System.out.print(k);21Tools for a solutionYou can synchronize an object:synchronized (obj) { ...code that uses/modifies obj... }No other code can use or modify this object at the same timeNotice that synchronized is being used as a statementYou can synchronize a method:synchronized void addOne(arg1, arg2, ...) { code }Only one synchronized method in a class can be used at a time (other methods can be used simultaneously)Synchronization is a tool, not a solution—multithreading is in general a very hard problem22The
View Full Document