• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Multithread
 

Multithread

on

  • 398 views

 

Statistics

Views

Total Views
398
Views on SlideShare
398
Embed Views
0

Actions

Likes
1
Downloads
27
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Multithread Multithread Presentation Transcript

    • Java II--Copyright © 2001-2002 Tom Hunter
    • Java II--Copyright © 2001-2002 Tom HunterChapter 15Multithreading
    • Java II--Copyright © 2001-2002 Tom Hunter• What is “Multi-threading?”15.1 Introduction: definitionthreadThe basic unit of program execution.A process can have several threads running concurrently,each performing a different job.When a thread has finished its job, it is suspended ordestroyed.http://java.sun.com/docs/books/tutorial/essential/threads/index.htmlAn Example of Threading
    • Java II--Copyright © 2001-2002 Tom Hunter15.1 Introduction• If anyone attempts tell you that C++ is better than Java,you only need to mention one word:ThreadingThreading
    • Java II--Copyright © 2001-2002 Tom Hunter• Threading is the ability to have multiple “simultaneous”lines of execution running in a single program.15.1 Introduction: unique to Java• Aside from Java, the language AdaAda—used by theDepartment of Defense—is the only other languagethat natively supports multi-threading.*concurrent“threads of execution”* The “language” C# (C-pound) has been alleged to “support” a form of multi-threading.
    • Java II--Copyright © 2001-2002 Tom Hunter• Since most computers have only one CPU, it is a myththat separate threads run simultaneously.15.1 Introduction: priority• Because they are sharing the cycles of the one CPU, eachthread is given a prioritypriority—which is a number from 1-10.( 5 is the default priority.)
    • Java II--Copyright © 2001-2002 Tom Hunter15.1 Introduction: priority• In fact, depending on the operating system, a thread’spriority can have a more drastic impact.• Threads with a higher priorityhigher priority number are given moremoreturnsturns at the CPU.
    • Java II--Copyright © 2001-2002 Tom Hunter• Depending on the OS, one of either two strategies is used:preemption ortimeslicing.15.1 Introduction: preemption• Under Sun’s Solaris operating system, a thread of acertain priority is allowed to run until it is finished, or until athread of higher priority becomes ready to run.
    • Java II--Copyright © 2001-2002 Tom Hunter15.1 Introduction: preemption• When a thread of higher priority arrives andsteals the processor from a lower-priority thread,this is known as preemptionpreemption.• One weakness of the preemption system is this:if another thread of the same priority is waitingto run, it is shut outshut out of the processor.This is called threadthread starvationstarvation.
    • Java II--Copyright © 2001-2002 Tom Hunter• Another system is used in the Windowsworld.• In a process known as timeslicing, eacheachthread is given a period of time to runthread is given a period of time to run, and thenall the other threads of equal priority get theirturn at the CPU.15.1 Introduction: timeslicing• As with the preemption system, undertimeslicing, a higher-priority thread stillcommandeers the CPU immediately.
    • Java II--Copyright © 2001-2002 Tom HunterClass Thread: an Overviewof theThread Methods
    • Java II--Copyright © 2001-2002 Tom Hunter• Class Thread has 7 different constructors.15.2 Class Thread Methods: Constructorsjava.lang.Thread• When we wish to make a Java program usethreading, the easiest way is to say our classextends the class Thread.
    • Java II--Copyright © 2001-2002 Tom HunterThread()—this constructor takes no arguments.1.) Every instantiated thread object has a name.—When we use the no-argument Constructor, thenames are automatically generated.A thread created using the Constructor abovewould be named:Thread-0, Thread-1, Thread-2, etc.
    • Java II--Copyright © 2001-2002 Tom HunterTo instantiate a Thread using this defaultConstructor, we would do like this:Thread t1 = new Thread();t1 would have the thread name of Thread-0.
    • Java II--Copyright © 2001-2002 Tom HunterThread( String name )—this Constructor takes a String argument,which becomes the thread’s name.String n = “cece”;Thread t2 = new Thread( n );t2 would have the thread name of cece.
    • Java II--Copyright © 2001-2002 Tom HunterThread( String name )—this Constructor takes a String argument,which becomes the thread’s name.String n = “cece”;Thread t3 = new Thread( n );Thread t4 = new Thread();t3 would have the thread name of cece.t4 would have the thread name of Thread-0.
    • Java II--Copyright © 2001-2002 Tom Hunter(There are 5 more Constructors with moreambitious intentions.For now, these two are sufficient.)
    • Java II--Copyright © 2001-2002 Tom HunterOnce we have instantiated a thread object,we’d like to put it to work. All of the work done by athread happens in the method:Normally, youyou will nevernever call the run() methodyourself. You will call anotheranother method—start() —and the JVMJVM will call run() whenit is good and ready.run()This method takes no arguments and returns void.
    • Java II--Copyright © 2001-2002 Tom Hunterpublic class MyThread extends Thread{}As you would expect, webegin by extending theclass Thread.
    • Java II--Copyright © 2001-2002 Tom Hunterpublic class MyThread extends Thread{public MyThread( String n ){super( n );System.out.println( “MyThread Constructor” );}}First, add the constructormethod—which names thethread “Thread-x”.Now, because it sub-classesThread, class MyThreadis an instance ofis an instance of the threadclass. Class Thread contains amethod run() that isempty—it does nothing.So, if you want anything tohappen in youryour thread, youneed to override the methodrun().public void run(){System.out.println( “In run!n” );}
    • Java II--Copyright © 2001-2002 Tom Hunterpublic class MyThread extends Thread{public MyThread( String n ){super( n );System.out.println( “MyThread Constructor” );}public void run(){System.out.println( “In run!n” );}public class TestMyThread{public static void main( String[] args ){}}Next we build a driver program andput in a method main. When mainexecutes, the JVM places it in asingle thread context.
    • Java II--Copyright © 2001-2002 Tom Hunterpublic class MyThread extends Thread{public MyThread( String n ){super( n );System.out.println( “MyThread Constructor” );}public void run(){System.out.println( “In run!n” );}public class TestMyThread{public static void main( String[] args ){}}MyThread chuck = new MyThread( "Charlie" );So, will we already be running athreadthread in main now?MyThread dede = new MyThread( ”Deirdra" );MyThread pat = new MyThread( “Patrick" );chuck.start();dede.start();pat.start();main() will instantiate and start() all these threads. After they havestarted, the methods immediately return and the thread main() dies.However the entire applicationentire application doesn’t die until the last thread does.
    • Java II--Copyright © 2001-2002 Tom Hunterpublic class MyThread extends Thread{public MyThread( String n ){super( n );System.out.println( “In Constructor” );}public void run(){System.out.println( “In run!n“ );}}public class TestMyThread{public static void main( String[] args ){MyThread chuck = new MyThread( “Charles” );chuck.start();MyThread dede = new MyThread( “Deirdra” );dede.start();MyThread pat = new MyThread( “Patrick” );pat.start();System.out.println( "chuck=" + chuck.toString() );System.out.println( " dede=" + dede.toString() );System.out.println( " pat=" + pat.toString() );}}chuck=Thread[Charlie,5,main]dede=Thread[Deirdra,5,main]pat=Thread[Patrick,5,main]•Thread name• priority• thread groupsBy default, a new thread has the samepriority as the thread that created it.
    • Java II--Copyright © 2001-2002 Tom HunterMyThread ConstructorIn run!MyThread ConstructorIn run!MyThread ConstructorIn run!chuck=Thread[Charlie,5,main]dede=Thread[Deirdra,5,main]pat=Thread[Patrick,5,main]MyThread chuck = new MyThread( “Charles” );chuck.start();Notice whathappened here—inour main method,we instantiated ourMyThread class.Then, we executed thestart() method of ourobject.We never called therun() method but,lo and beholdlo and behold, it got called.
    • Java II--Copyright © 2001-2002 Tom HunterSo, how many threads did we givelife to in that example?4mainchuck,dede,pat
    • Java II--Copyright © 2001-2002 Tom HunterSo, using threads is much like running a road race:—Before running, you must startstart….1.) So, let’s understand the sequence:—My program is running along happily.Without me doing anything, myprogram is already running in athread—main.(Therefore, your programs have alwaysalwaysbeen running in a single thread.)
    • Java II--Copyright © 2001-2002 Tom Hunter2.) In this context—where a single thread (main) isalready running—you’re going to executethe following code:public static void main( String[] args ){MyThread mt = new MyThread();mt.start();}Firstly, understand that your goal is to start up a newnew thread.When you instantiate a new thread object, and then execute itsstart() method, you are asking the JVM to create a new,additional thread to run alongside the thread you created when youroriginal main() method started up.We say that start()launches a new threadlaunches a new thread,and then returns to thecalling program, therebypermitting the callingprogram to continueworking independently ofthe just-launched thread.
    • Java II--Copyright © 2001-2002 Tom Hunterpublic static void main( String[] args ){MyThread mt = new MyThread();mt.start();}mt.run();Question: what wouldwould happen if you yourself executed themethod run() in your MyThread class?Although you have a method run() in your MyThreadclass, don’t ever execute the run() method yourself. Letthe JVM do it for you after you execute the start()method.Answer: you would execute the run() method in the same thread—thread main—that you were already in, not in a new thread.
    • Java II--Copyright © 2001-2002 Tom Hunterpublic static void main( String[] args ){MyThread chuck = new MyThread( “Charlie” );chuck.start();MyThread dede = new MyThread( “Deirdra” );dede.start();MyThread pat = new MyThread( “Patrick” );pat.start();}public class MyThread extends Thread{public MyThread( String name ){super( name );}public run(){System.out.println( “In run()-thread=“ + Thread.currentThread() );}}What will be theoutput when weexecute main()?In run()-thread=Thread[Charlie,5,main]In run()-thread=Thread[Deirdra,5,main]In run()-thread=Thread[Patrick,5,main]
    • Java II--Copyright © 2001-2002 Tom Hunterpublic static void main( String[] args ){MyThread chuck = new MyThread( “Charlie” );chuck.start();MyThread dede = new MyThread( “Deirdra” );dede.start();dededede.run();.run();MyThread pat = new MyThread( “Patrick” );pat.start();}public class MyThread extends Thread{public MyThread( String name ){super( name );}public run(){System.out.println( “In run()-thread=“ + Thread.currentThread() );}}What will be theoutput NOW whenwe executemain()?Notice, I added astatement:dede.run();In run()-thread=Thread[Charlie,5,main]In run()-thread=Thread[Deirdra,5,main]In run()-thread=Thread[In run()-thread=Thread[mainmain,5,main],5,main]In run()-thread=Thread[Patrick,5,main]
    • Java II--Copyright © 2001-2002 Tom HunterSo, pretend you areholding the starter pistol for aroad race.You start the threads, butlet them do the running.
    • Java II--Copyright © 2001-2002 Tom HunterIf you try to execute a start() methodon a thread that has already been started,the start() method throws anIllegalThreadStateException
    • Java II--Copyright © 2001-2002 Tom HunterA Survey ofstaticThread Methods
    • Java II--Copyright © 2001-2002 Tom Hunter15.2 A Survey of static Thread MethodsMany thread methods are static :A static method belongs to the class—not toany one instance of the class.Therefore, you can execute a static methodeven if you haven’t instantiated the class—such as thecase of main.( Review: what does it mean when a method isstatic? )
    • Java II--Copyright © 2001-2002 Tom Hunter15.2 An Overview of the Thread Methodsstatic void sleep( long millisecs )—Causes the currently executing thread to sleep(meaning temporarily cease execution) for thespecified number of milliseconds.—During this sleep time the thread does notdoes notuseuse any resources of the processor.(Good Test Question…)
    • Java II--Copyright © 2001-2002 Tom Hunter15.2 An Overview of the Thread Methodsstatic Thread currentThread()—Returns a reference to the currently executingthread object.—In other words, if you want to know whichthread is currently executing, you execute thismethod…. and what would be the syntax to dothat?Thread x;x = Thread.currentThread();
    • Java II--Copyright © 2001-2002 Tom Hunter15.2 An Overview of the Thread Methodsstatic void yield()—Causes the currently executing thread object totemporarily pause and allow other threads of equalpriority to execute.—You would use the method yield() only ifyour operating system did not support preemptivemultithreading.
    • Java II--Copyright © 2001-2002 Tom HunterAttention!The static thread methodshave one thing in common:they all operate on thecurrent threadcurrent thread..
    • Java II--Copyright © 2001-2002 Tom HunterThree Methods withSimilar Namesthat areTherefore Confusing
    • Java II--Copyright © 2001-2002 Tom Hunterstatic boolean interrupted()boolean isInterrupted()void interrupt()Is the currentcurrent thread interrupted?Is a certaincertain namednamedthread interrupted?InterruptInterrupt this thread !
    • Java II--Copyright © 2001-2002 Tom Hunter15.2 A Survey of the Thread Methodsstatic boolean interrupted()—True or False.—TestsTests whether or not the current thread has beeninterrupted recently.—This static method discovers whether or not thecurrent thread has been interrupted.—Calling this method also resets the “interrupted”status of its argument.
    • Java II--Copyright © 2001-2002 Tom Hunter15.2 A Survey of the Thread Methodsstatic boolean interrupted()—This particular method can be easily confusedwith another method similarly named.—The emphasis here is on CURRENT THREAD.—For this method, we don’t get to choose thethread we wish to test. By default, it tests whetheror not the current thread is interrupted.
    • Java II--Copyright © 2001-2002 Tom Hunter15.2 A Survey of the Thread Methodsboolean isInterrupted()—Tests whether or not THIS thread has beeninterrupted. This method can be used to discoverwhether any thread has been interrupted.—Also, calling this method does NOT change theinterrupted status of its argument.
    • Java II--Copyright © 2001-2002 Tom Hunter15.2 A Survey of the Thread Methodsvoid interrupt()—Interrupts thisthis thread. If called on a thread objectthat is already currently blocked, the blocking call(such as sleep() or wait() complains aboutthe interrupt() call and terminates with anInterruptedException.—Sends an interrupt message to a thread. The“interrupted” status of the thread is set to true.This doesn’t ask aquestion, it performsan actionaction
    • Java II--Copyright © 2001-2002 Tom Hunter15.2 A Survey of the Thread Methodsvoid wait()—The thread itself calls the wait() method towait for a specific condition to be satisfied.
    • Java II--Copyright © 2001-2002 Tom Hunter15.2 A Survey of the Thread Methodsboolean isAlive()—returns true if:• start() has been called for the thread, and• the thread is not yet dead, meaning• the run() method has not yet finished anddied.
    • Java II--Copyright © 2001-2002 Tom Hunter15.2 A Survey of the Thread MethodsString getName()—returns the thread name for the thread.• don’t mistake this for the reference to thethread.
    • Java II--Copyright © 2001-2002 Tom Hunter15.2 A Survey of the Thread Methodsvoid setName( String n )—sets the thread name for the thread.
    • Java II--Copyright © 2001-2002 Tom Hunter15.2 A Survey of the Thread Methodsstatic void dumpStack()—causes a dump of the execution stack at this instant.• this has great potential—learn how to use it.
    • Java II--Copyright © 2001-2002 Tom Hunterpublic class MyThread extends Thread{public MyThread(){System.out.println( “MyThread Constructor” );}}We start off with our typical classMyThread that extends Thread.
    • Java II--Copyright © 2001-2002 Tom Hunterpublic class MyThread extends Thread{public MyThread( String n ){super( n );System.out.println( “MyThread Constructor” );}}public class TestMyThread{public static void main( String[] args ){MyThread pat = new MyThread();pat.start();Thread.dumpStack();}}We instantiate athread object,and execute thestart()method.Now, because the threadmethod dumpStack() isstatic, we call it on the classobject.
    • Java II--Copyright © 2001-2002 Tom HunterMyThread Constructorjava.lang.Exception: Stack tracejava.lang.Throwable(java.lang.String)java.lang.Exception(java.lang.String)void java.lang.Thread.dumpStack()void TestMyThread.main(java.lang.String [])After dumpStack()You seemain()was the firstthingexecuted.You read a stack dump fromfromthe bottom upthe bottom up, the way itwas stacked.Next, Thread’sstatic methoddumpStack()was called.Finally Exception was called,followed by Throwable, theSuperclass.
    • Java II--Copyright © 2001-2002 Tom Hunter15.2 A Survey of the Thread Methodsfinal void setPriority( int p )—This method allows you the change the priorityto an integer between 1 and 10.
    • Java II--Copyright © 2001-2002 Tom Hunter15.2 A Survey of the Thread Methodsfinal int getPriority()—This method lets you return the priority for athread.—Notice, this method is final to prevent you fromcausing any mischief.
    • Java II--Copyright © 2001-2002 Tom HunterThread States:Life Cycle of a Thread
    • Java II--Copyright © 2001-2002 Tom Hunter• born15.3 Thread States: LifeLife Cycle of a Thread• ready• running• deadThread is InstantiatedWhen start() method is called,thread enters ready state.•Highest priority thread that is readyenters running stateSystem assigns a processor to thethread and the thread begins toexecute its run() method.When run() method completes orterminates, thread enters dead state.•Thread marked to be removed fromthe system.Entered when run() terminates orthrows uncaught exception.
    • Java II--Copyright © 2001-2002 Tom Hunter• blocked15.3 Thread States: WorkingWorking Cycle of a Thread• sleeping• waiting
    • Java II--Copyright © 2001-2002 Tom Hunter• blocked15.3 Thread States: WorkingWorking Cycle of a ThreadTo enter blocked state, thread must alreadyhave been in running state.Even if the CPU is available, ablocked threadblocked thread cannot use the processor.Common reason for a thread being in ablocked state—waiting on a request for fileI/O .
    • Java II--Copyright © 2001-2002 Tom Hunter• sleeping15.3 Thread States: WorkingWorking Cycle of a ThreadEntered when sleep() method has beencalled for a thread.While in the sleep state, a thread cannot usethe processor.After its sleep time expires, the thread re-enters the ready state.It doesn’t starting running againIt doesn’t starting running again, itbecomes eligibleeligible to run—much in the sameway it did when you called the start()method.
    • Java II--Copyright © 2001-2002 Tom Hunter• waiting15.3 Thread States: WorkingWorking Cycle of a ThreadEntered when wait() method has beencalled in an object thread is accessing.One waiting thread becomes readyready whenobject calls the method notify().When the method notifyAll() hasbeen called—all waiting threads becomeready.
    • Java II--Copyright © 2001-2002 Tom Hunter• A thread executes until:—it dies,—it calls sleep(),—it calls wait(),—it calls yield(),—its quantum of time is used up, or—it is preempted by a higher priority thread.15.3 Thread States: Life Cycle of a Thread
    • Java II--Copyright © 2001-2002 Tom Hunter• This graphic illustrates the life of a thread.15.3 Thread States: Life Cycle of a ThreadWhen a thread has just been instantiated, your onlyoption is to start() it. If you try to execute anymethod besides start(), you will cause anIllegalThreadStateException• When the start() method is returns the thread is readyto be run when the scheduler decides it’s the right time.
    • Java II--Copyright © 2001-2002 Tom Hunter• Notice on the right there is the state called “notrunnable.” There are several reasons why a thread thathas not finished its run() method could find itself“not runnable.”15.3 Thread States: Life Cycle of a Thread
    • Java II--Copyright © 2001-2002 Tom Hunter• If a thread has been put to sleepsleep, then the sleep milliseconds mustelapse.• If a thread is waitingwaiting for something, then another object must notifynotifythe waiting thread of a change in condition.—The other object would handle the notification bycalling the methods notify() or notifyAll().• If a thread is blocked on I/O, then the I/O must complete.15.3 Thread States: Life Cycle of a Thread
    • Java II--Copyright © 2001-2002 Tom Hunter• Let’s make sure we have that sequence straight:—Thread zeldazelda is waiting for something else.—Because it cannot go on without the something it’swaiting for, zeldazelda calls the method wait() onitself: zelda.wait();—Thread zeldazelda remains in the waiting state until theobject it is waiting, say scottscott, announces it isready by issuing the notify() ornotifyAll()method.15.3 Thread States: Life Cycle of a Thread
    • Java II--Copyright © 2001-2002 Tom HunterThreadSynchronization
    • Java II--Copyright © 2001-2002 Tom Hunter• Until this point, all of our threads have lived alone.• However, it’s possible to have threads share information.• In a class, it is common for many threads to all haveaccess to instance variables that have class scope.15.5 Thread Synchronization• However, this usually raises issues that could never arisewhen threads were not involved.• For example, what happens when two threads try to writeto or read from an instance variable at the same instant?
    • Java II--Copyright © 2001-2002 Tom Hunter• Coping with this problem raises the thorny subject ofthread synchronization.15.5 Thread Synchronizationpublic synchronized intgetBalance(){…}
    • Java II--Copyright © 2001-2002 Tom Hunter• The first piece of the puzzle is a thing called a monitor.• When we say an object is a monitor, we are merely sayingthat object has the ability to pay attention to the behavior ofthreads.• We say a “monitor” is an object that monitors threads.• Any object can be a monitor.15.5 Thread Synchronization: monitors
    • Java II--Copyright © 2001-2002 Tom Hunter• We accomplish thread synchronization by makingmethods synchronized.• Further, we say every object that contains synchronizedthreads is in effect a monitor.• If an object is a monitor, then that objectpermits only one thread at a time to execute asynchronizedsynchronized method on that object.15.5 Thread Synchronization: monitors
    • Java II--Copyright © 2001-2002 Tom Hunter• This is implemented as follows:—whenever a synchronized method is invoked, theobject is locked.—in other words: if my object has a synchronizedmethod, and something calls that synchronizedmethod, then my object is locked up tight.• In fact, for every Java object that contains a synchronizedmethod, Java creates a lock associated with that object.15.5 Thread Synchronization: locks
    • Java II--Copyright © 2001-2002 Tom Hunterpublic class LockBox{private int contents;private boolean available = false;public synchronized int get(){return contents;}public synchronized void put( int value ){contents = value;}}Note that methodsget() and put() areeach synchronized.Because the class LockBox contains a synchronized method,every instance of class LockBox would have a special lockassociated with it.If my class were calling the put() method, then nobodycould call either the put() or the get() method in thatinstance. I have locked up that instance and it’s hands off foreverybody until I’m done.
    • Java II--Copyright © 2001-2002 Tom Hunterpublic class LockBox{private int contents;private boolean available = false;public synchronized int get(){return contents;}public synchronized void put( int value ){contents = value;}}So, you see: when somebody is puttingputting a value to thecontents variable, nobody else can get it untilthe put is done.Likewise, when somebody is gettinggetting the valuecurrently in the contents variable, nobody elsecan change that value in the middle of the read.
    • Java II--Copyright © 2001-2002 Tom Hunter• In other words, if an object has more than onesynchronized method, then only one of thosesynchronized methods at a time can be executing.• Synchronized methods are like having a single bathroom—no matter how many need it, it can only be used by oneperson—boy or girl—at a time.15.5 Thread Synchronization• When the synchronized method is done executing,it releases the lock.• The monitor gives the go ahead to the highest-prioritythread that is readyready to execute the synchronizedmethod.
    • Java II--Copyright © 2001-2002 Tom Hunter• If a synchronized method gets its turn to execute but then—during that execution—it finds it cannot proceed( maybe I/O is blocked or there’s some other hold up) —then the thread may voluntarily call its method wait().• In the wait() state, the thread doesn’t take up processorresources and doesn’t hold a lock on the monitor.15.5 Thread Synchronization: wait()
    • Java II--Copyright © 2001-2002 Tom Hunter• When a thread executing a synchronized methodcompletes, the thread can execute the notify() method.• Executing the notify() method tells any waitingthreads to become ready so the scheduler can get them backrunning again.15.5 Thread Synchronization: notify()• The notify() method is like calling:“Head up, you’re on deck.”• After a thread has been notified, it can attempt to get a lockon the object.
    • Java II--Copyright © 2001-2002 Tom Hunter• Similarly, if a synchronized method no longer needs its lockfor some reason, it can call notifyAll(), which alerts allwaiting threads that they are free to enter the ready modeand again attempt to get a lock on the object.15.5 Thread Synchronization: notifyAll()• Warning: if a thread is waiting, it may wait forever—in a state called deadlock—unless some otherthread notifies it that it can enter the ready state.• So, if you ever make something wait() be sure towake it up!
    • Java II--Copyright © 2001-2002 Tom Hunter• When an object is a monitor, that means it keeps a list of allthreads that wish to execute synchronized methods.15.5 Thread Synchronization: notifyAll()
    • Java II--Copyright © 2001-2002 Tom Hunter• Just as a method alone can be synchronized, it is possibleto just place curly brackets around a chunk of code with thekeyword this as an argument.• That means, while the tiny block of code so isolated isexecuting, the object referred to by the this is locked.15.5 Thread Synchronization: blocks of code
    • Java II--Copyright © 2001-2002 Tom HunterBe Careful: synchronization shouldbe used like a spice, not a gravy.It’s overuse can spoil yourapplication and slow it way downslow it way down.Beware!
    • Java II--Copyright © 2001-2002 Tom HunterProducer/ConsumerRelationshipwithoutwithoutThread Synchronization
    • Java II--Copyright © 2001-2002 Tom Hunter• The LockBox class we just saw was of a type known asthe Producer/Consumer.• One thread Produces something while another Consumes.15.6 Producer/Consumer Relationship withoutThread Synchronization
    • Java II--Copyright © 2001-2002 Tom Hunter• The Producer thread writes to abuffer, while the...• Consumer thread reads from thatsame buffer.
    • Java II--Copyright © 2001-2002 Tom Hunter• Say we were selling peaches… [with[withoutout synchronization]synchronization]i.) Consumer asks me for 35 pounds of peaches.ii.) I Produce the 35 pounds of peaches, weigh them and write downthe total bill on a chalk slate.iii.) My partner Luigi bags the peaches, reads the price on the slate andtakes the money.iv.) But I’m much faster than Luigi, so by the time he gets the peachesbagged, I’ve already erased the slate and put the next price down there,which was for 5 pounds of peaches.v.) Result: Consumer pays for 5 pounds of peaches, walks with 35pounds and Luigi and I go out of business.
    • Java II--Copyright © 2001-2002 Tom Hunter• Say we were selling peaches… [ withwith synchronizationsynchronization ]i.) Consumer asks me for 35 pounds of peaches.ii.) I Produce the 35 pounds of peaches, weigh them and write downthe total bill on a chalk slate.iii.) My partner Luigi bags the peaches, reads the price on the slate andtakes the money.iv.) I’m much faster than Luigi, so I—the Producer—call a wait().v.) When Luigi is caught up he will notify() mevi.) Result: Consumer gets annoyed because of the delay but we stay inbusiness because our operations are synchronized.