Chapter 24 Multithreading

Chapter 16 Applets and Multimedia

Chapter 24 Multithreading Chapter 18 Binary I/O Chapter 25 Networking Chapter 16 Applets and Multimedia Chapter 26 Internationalization

Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

1

Objectives
To understand the concept of multithreading and apply it to develop animation (§24.2). To develop task classes by implementing the Runnable interface in cases of multiple inheritance (§24.4). To create threads to run tasks using the Thread class (§24.3). To control animations using threads (§§24.5, 24.7). To run code in the event dispatcher thread (§24.6) . To execute tasks in a thread pool (§24.8). To use synchronized methods or block to synchronize threads to avoid race conditions (§24.7.1). To synchronize threads using locks (§24.10) . To facilitate thread communications using conditions on locks (§§24.11-24.12). To use blocking queues to synchronize access to an array queue, linked queue, and priority queue (§24.13 Optional). To restrict number of accesses to a shared resource using semaphores (§24.14 Optional). To use the resource ordering technique to avoid deadlock (§24.7.4). To understand the life cycle of a thread (§24.16). To create synchronized collections using the static methods in the Collections class (§24.17). To display the completion status of a task using JProgressBar (§24.18 Optional).
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

2

Threads Concept
Multiple threads on multiple CPUs Multiple threads sharing a single CPU
Thread 1 Thread 2 Thread 3

Thread 1 Thread 2 Thread 3

Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

3

Creating Tasks and Threads
java.lang.Runnable TaskClass
// Client class public class Client { ... public void someMethod() { ... // Create an instance of TaskClass TaskClass task = new TaskClass(...); // Create a thread Thread thread = new Thread(task); // Start a thread thread.start(); ... } ... }

// Custom task class public class TaskClass implements Runnable { ... public TaskClass(...) { ... } // Implement the run method in Runnable public void run() { // Tell system how to run custom thread ... } ... }

Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

4

Example: Using the Runnabel Interface to Create and Launch Threads
Objective: Create and run three threads:
± The first thread prints the letter a 100 times. ± The second thread prints the letter b 100 times. ± The third thread prints the integers 1 through 100.
TaskThreadDemo
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6

Run
5

Runnable java. Interrupts this thread. Causes this thread to temporarily pause and allow other threads to execute. Liang.lang. Creates a thread for a specified task. 0-13-148952-6 6 . (c) 2005 Pearson Education. Starts the thread that causes the run() method to be invoked by the JVM. Introduction to Java Programming. Sets priority p (ranging from 1 to 10) for this thread.Thread +Thread() +Thread(task: Runnable) +start(): void +isAlive(): boolean +setPriority(p: int): void +join(): void +sleep(millis: long): void +yield(): void +interrupt(): void Creates a default thread. Puts the runnable object to sleep for a specified time in milliseconds. All rights reserved.lang. Waits for this thread to finish. Tests whether the thread is currently running. Inc.The Thread Class «interface» java. Sixth Edition.

Thread States  A thread can be in one of Four states for threads: new. blocked. Introduction to Java Programming. resume. runnable. Sixth Edition. 0-13-148952-6 7 . (c) 2005 Pearson Education. dead sleep done sleeping suspend resume blocked new start await signal runnable Wait for lock Lock available block on I/O run exits stop dead I/O complete Note: suspend.stop deprecated. All Liang. rights reserved. Inc.

0-13-148952-6 8 . There can be many runnable threads. But only one of them can be running at any time point. OS decides which thread to run. it is in the new state. Inc. All rights reserved. the thread becomes runnable.     A runnable thread might not be running.Thread States  When a thread has just been created using the new operator. More on this later. Once start method is invoked (which calls the run method). new start runnable Liang. (c) 2005 Pearson Education. Introduction to Java Programming. Sixth Edition.

4. (c) 2005 Pearson Education. The thread is currently running and method Thread.sleep is called suspend method of the thread is called. The thread tries to lock an object locked by another thread.Thread States  A runnable thread enters the blocked state when 1. sleep suspend await blocked A blocked thread cannot be running runnable Wait for lock block on I/O Liang. 2. Introduction to Java Programming. All rights reserved. (deprecated) The thread calls the await method. The thread calls an operation that is blocked on i/o. Inc. 5. 3. 0-13-148952-6 9 . Sixth Edition.

3. It has slept the specified amount of time. 2. 4. All rights reserved. done sleeping blocked resume signal runnable Lock available I/O complete Liang. Inc. (c) 2005 Pearson Education. resume method of the thread is called.Thread States  A blocked reenters runnable state when 1. (deprecated) Another method calls signal or signalAll Object lock released by other thread I/O completed. 0-13-148952-6 10 . 5. Introduction to Java Programming. Sixth Edition.

Inc. (deprecated) An exception is thrown but not caught.Thread States  A runnable thread enters the dead state when    Its run method exits. Introduction to Java Programming. All rights reserved. Sixth Edition. Natural death. 0-13-148952-6 11 . stop method of the thread is called. (c) 2005 Pearson Education. runnable run exits stop dead Liang.

Introduction to Java Programming. All rights reserved. or blocked. Liang. 0-13-148952-6 12 .Thread States Finding out states of threads ± Method isAlive allows you to find out whether a thread is alive or dead.  false if the thread is still new and not yet runnable or if the thread is dead  This ± No way to find out whether an alive thread is running. (c) 2005 Pearson Education. Inc. method returns true if the thread is runnable or blocked. runnable. Sixth Edition.

0-13-148952-6 13 .out. For example.yield(). Introduction to Java Programming. Sixth Edition. So. } } Every time a number is printed. Thread. i++) { System. Liang. the print100 thread is yielded.The Static yield() Method You can use the yield() method to temporarily release time for other threads. (c) 2005 Pearson Education. All rights reserved.java as follows: public void run() { for (int i = 1. suppose you modify the code in Lines 57-58 in TaskThreadDemo. the numbers are printed after the characters. i <= lastNum.print(" " + i). Inc.

Inc. Liang. i++) { System. i <= lastNum.print(" " + i). try { if (i >= 50) Thread. 0-13-148952-6 14 . All rights reserved. suppose you modify the code in Lines 56-60 in TaskThreadDemo. For example.java as follows: public void run() { for (int i = 1. the print100 thread is put to sleep for 1 millisecond. Introduction to Java Programming.The Static sleep(milliseconds) Method The sleep(long mills) method puts the thread to sleep for the specified time in milliseconds. (c) 2005 Pearson Education.sleep(1). Sixth Edition. } catch (InterruptedException ex) { } } } Every time a number (>= 50) is printed.out.

It might happen that the t1 is select to run again. Introduction to Java Programming. Inc. Sixth Edition. yield There is a big difference ± Calling sleep put the current running thread into the blocked state ± Calling yield does not put the calling thread. All rights reserved.sleep vs. Liang. (c) 2005 Pearson Education. 0-13-148952-6 15 . t1 into the blocked state It merely let the scheduler kick in and pick another thread to run. This happens when t1 has a higher priority than all other runnable threads.

i++){ System.java as follows: public void run(){ Thread thread4 = new Thread(new PrintChar('c'. thread4. Sixth Edition.The join() Method You can use the join() method to force one thread to wait for another thread to finish. Introduction to Java Programming. 60)).join(). } } catch (InterruptedException ex) { } } The numbers after 50 are printed after thread4 is finished. Liang. suppose you modify the code in Lines 56-60 in TaskThreadDemo. try { for (int i = 1. (c) 2005 Pearson Education. if (i == 50) thread4. 0-13-148952-6 16 . All rights reserved. For example.print(" " + i). i < lastNum.start().out. Inc.

Inc.InterruptedException is thrown.io. It returns true if a thread is in the Ready. The interrupt() method interrupts a thread in the following way: If a thread is currently in the Ready or Running state. 0-13-148952-6 17 . it is awakened and enters the Ready state. Introduction to Java Programming. if a thread is currently blocked. Liang.isAlive(). Sixth Edition. it returns false if a thread is new and has not started or if it is finished. its interrupted flag is set. (c) 2005 Pearson Education. The isInterrupt() method tests whether the thread is interrupted. or Running state. and isInterrupted() The isAlive() method is used to find out the state of a thread. and an java. Blocked. All rights reserved. interrupt().

(c) 2005 Pearson Education. All rights reserved. 0-13-148952-6 18 . Introduction to Java Programming. Sixth Edition. Inc.Outline Introduction: Why and what Basics: creating and running threads Issues ± Thread states ± Thread scheduling ± Synchronization ± Suspending and stopping threads Uses ± Animation ± Threads and Swing Liang.

The thread scheduler decides which runnable thread to run. there might be many runnable threads. Inc. or Another thread with higher priority moves out of blocked state Then the thread scheduler kicks in and picks another thread with the highest priority to run Liang. Introduction to Java Programming. 0-13-148952-6 19 . (c) 2005 Pearson Education. Questions: When does the thread scheduler kick in and pick a thread to run? How does the thread scheduler select among the runnable threads? A not-so-precise answer: A running Java thread will continue to run until It calls yield method. Sixth Edition. All rights reserved. But only one of them is actually running.Thread Scheduling At any time. or It ceases to be runnable (dead or blocked).

(c) 2005 Pearson Education. It keeps a running thread active until a higher-priority thread awakes and takes control.g.  Liang. Interrupts the running thread periodically to give other threads a chance to run. Inc. Introduction to Java Programming. 0-13-148952-6 20 . Solaris) Does not perform time-slicing. All rights reserved. ³Green thread´ implementation (e.g. Windows): Performs time-slicing.Thread Scheduling  Two different thread implementations  ³Native thread´ implementation (e. Sixth Edition.

Introduction to Java Programming. (c) 2005 Pearson Education. or Another thread with higher priority moves out of blocked state. Then the thread scheduler kicks in and picks another thread with the highest priority to run Liang. Sixth Edition. All rights reserved. or It is pre-emptied by OS (time-slicing). or It ceases to be runnable (dead or blocked). Inc. For the native thread implementation. the precise answer is A running Java thread will continue to run until It calls yield method. 0-13-148952-6 21 .Thread Scheduling The answer on slide 19 is precise for the green thread implementation.

Introduction to Java Programming.NORM_PRIORITY Liang. Inc.MIN_PRIORITY Thread. (c) 2005 Pearson Education. 0-13-148952-6 22 . Some constants for priorities include Thread. You can reset the priority using setPriority(int priority).Thread Priority Each thread is assigned a default priority of Thread. All rights reserved.MAX_PRIORITY Thread.NORM_PRIORITY. Sixth Edition.

Inc.Example: Flashing Text FlashingText Run Liang. (c) 2005 Pearson Education. 0-13-148952-6 23 . All rights reserved. Introduction to Java Programming. Sixth Edition.

Introduction to Java Programming. 0-13-148952-6 24 . (c) 2005 Pearson Education. This ensures that each event handler finishes executing before the next one executes and the painting isn¶t interrupted by events. Liang. called the event dispatcher thread. Sixth Edition. All rights reserved. Inc.GUI Event Dispatcher Thread GUI event handling and painting code executes in a single thread.

The invokeLater method returns immediately.invokeLater and invokeAndWait In certain situations. you need to run the code in the event dispatcher thread to avoid possible deadlock. You must put this code in the run method of a Runnable object and specify the Runnable object as the argument to invokeLater and invokeAndWait. Introduction to Java Programming.SwingUtilities class to run the code in the event dispatcher thread. 0-13-148952-6 25 . The invokeAndWait method is just like invokeLater. without waiting for the event dispatcher thread to execute the code. Liang.swing. invokeLater and invokeAndWait. (c) 2005 Pearson Education. Inc. Sixth Edition. in the javax. You can use the static methods. All rights reserved. except that invokeAndWait doesn't return until the event-dispatching thread has executed the specified code.

Sixth Edition. Introduction to Java Programming.invokeLater(new Runnable() { public void run() { // Place the code for creating a frame and setting it properties } }). 0-13-148952-6 Run 26 . } EventDispatcherThreadDemo Liang. In certain situations. To avoid possible thread deadlock. however. (c) 2005 Pearson Education. it could cause problems. Inc. This works fine for most applications. All rights reserved. you have launched your GUI application from the main method by creating a frame and making it visible.Launch Application from Main Method So far. you should launch GUI creation from the event dispatcher thread as follows: public static void main(String[] args) { SwingUtilities.

the applet announces. Sixth Edition. (c) 2005 Pearson Education. All rights reserved. "eight o¶clock twenty minutes p.m. Introduction to Java Programming.m.Case Study: Clock with Audio (Optional) The example creates an applet that displays a running clock and announces the time at one-minute intervals. if the current time is 6:30:00. Inc. 0-13-148952-6 . the applet announces." Also add a label to display the digital time." If the current time is 20:20:00. ClockWithAudio Run 27 Liang. For example. "six o¶clock thirty minutes a.

Thus. you should announce the time on a separate thread. This can be accomplished by modifying the announceTime method. and third seconds of the minute. Introduction to Java Programming. All rights reserved. you will notice that the second hand does not display at the first.Run Audio on Separate Thread When you run the preceding program. ClockWithAudioOnSeparateThread Run 28 Liang. This is because sleep(1500) is invoked twice in the announceTime() method. the time is not updated and the clock was not repainted for these three seconds. To fix this problem. which takes three seconds to announce the time at the beginning of each minute. the next action event is delayed for three seconds during the first three seconds of each minute. (c) 2005 Pearson Education. 0-13-148952-6 . Sixth Edition. Inc. As a result of this delay. second.

concurrent. «interface» java. JDK 1. Inc. Introduction to Java Programming. Returns a list of unfinished tasks.Thread Pools Starting a new thread for each task could limit throughput and cause poor performance. Returns true if the executor has been shutdown. ExecutorService is a subinterface of Executor. A thread pool is ideal to manage the number of tasks executing concurrently.ExecutorService +shutdown(): void +shutdownNow(): List<Runnable> Shuts down the executor. but allows the tasks in the executor to complete. Shuts down the executor immediately even though there are unfinished threads in the pool. 0-13-148952-6 29 .5 uses the Executor interface for executing tasks in a thread pool and the ExecutorService interface for managing and controlling tasks. it cannot accept new tasks. \ «interface» java. (c) 2005 Pearson Education.Executor +execute(Runnable object): void Executes the runnable task. All rights reserved.util. +isShutdown(): boolean +isTerminated(): boolean Liang. Returns true if all tasks in the pool are terminated.util. Sixth Edition.concurrent. Once shutdown.

0-13-148952-6 . +newCachedThreadPool(): Creates a thread pool that creates new threads as needed. use the static methods in the Executors class.concurrent.Creating Executors To create an Executor object.Executors +newFixedThreadPool(numberOfThreads: Creates a thread pool with a fixed number of threads executing int): ExecutorService concurrently. Inc.util. All rights reserved. java. A thread may be reused to execute another task after its current task is finished. ExecutorDemo Run 30 Liang. Sixth Edition. Introduction to Java Programming. (c) 2005 Pearson Education. but ExecutorService will reuse previously constructed threads when they are available.

For example. thread[j] Liang. 0-13-148952-6 31 .setBalance(newBalance). (c) 2005 Pearson Education. Sixth Edition. All rights reserved. Inc.getBalance() + 1. newBalance = bank. Introduction to Java Programming.getBalance() + 1. Step 1 2 3 4 balance 0 0 1 1 thread[i] newBalance = bank. bank.setBalance(newBalance). two unsynchronized threads accessing the same bank account may cause conflict. bank.Thread Synchronization A shared resource may be corrupted if it is accessed simultaneously by multiple threads.

Suppose that you create and launch one hundred threads.Runnable 100 1 1 1 AddAPennyTask +run(): void AccountWithoutSync -bank: Account -thread: Thread[] Account -balance: int +getBalance(): int +deposit(amount: int): void +main(args: String[]): void AccountWithoutSync Run Liang.Example: Showing Resource Conflict Objective: Write a program that demonstrates the problem of resource conflict. Introduction to Java Programming. java. Inc.lang. each of which adds a penny to an account. (c) 2005 Pearson Education. Assume that the account is initially empty. All rights reserved. Sixth Edition. 0-13-148952-6 32 .

All rights reserved. Inc. The effect of this scenario is that Task 1 did nothing. caused the error in the example? Here is a possible scenario: Step 1 2 3 4 ). the problem is that Task 1 and Task 2 are accessing a common resource in a way that causes conflict. A class is said to be threadsafe if an object of the class does not cause a race condition in the presence of multiple threads. Obviously. This is a common problem known as a race condition in multithreaded programs. balance = newBalance. Introduction to Java Programming. because in Step 4 Task 2 overrides Task 1's result. then. 0-13-148952-6 33 . As demonstrated in the preceding example. (c) 2005 Pearson Education. Sixth Edition. Liang. Task 2 newBalance = balance + 1.Race Condition What. balance = newBalance. balance 0 0 1 1 Task 1 newBalance = balance + 1. the Account class is not thread-safe.

(c) 2005 Pearson Education. known as critical region. The critical region in the Listing 24. Introduction to Java Programming. There are several ways to correct the problem in Listing 24. Inc.7.The synchronized keyword To avoid resource conflicts. one approach is to make Account thread-safe by adding the synchronized keyword in the deposit method in Line 45 as follows: public synchronized void deposit(double amount) Liang. Sixth Edition. it is necessary to prevent more than one thread from simultaneously entering certain part of the program. All rights reserved.7 is the entire deposit method. 0-13-148952-6 34 . You can use the synchronized keyword to synchronize the method so that only one thread can access the method at a time.

then the method is executed. Sixth Edition. the lock of that object (respectively. All rights reserved. Liang. (c) 2005 Pearson Education.Synchronizing Instance Methods and Static Methods A synchronized method acquires a lock before it executes. In the case of an instance method. In the case of a static method. Introduction to Java Programming. If one thread invokes a synchronized instance method (respectively. and finally the lock is released. static method) on an object. the lock is on the class. 0-13-148952-6 35 . the lock is on the object for which the method was invoked. Inc. class) is acquired first. class) is blocked until the lock is released. Another thread invoking the same method of that object (respectively.

the preceding scenario cannot happen. Task 2 is blocked until Task 1 finishes the method. and Task 1 is already in the method. (c) 2005 Pearson Education. If Task 2 starts to enter the method. All rights reserved. Sixth Edition. Task 1 Acquire a lock on the object account Task 2 Execute the deposit method Wait to acquire the lock Release the lock Acqurie a lock on the object account Execute the deposit method Release the lock Liang.Synchronizing Instance Methods and Static Methods With the deposit method synchronized. 0-13-148952-6 36 . Introduction to Java Programming. Inc.

0-13-148952-6 37 . Liang. This block is referred to as a synchronized block. and invoking a synchronized static method of a class acquires a lock on the class. Sixth Edition. Inc. the thread is blocked until the lock is released. the statements in the synchronized block are executed. If the object is already locked by another thread.Synchronizing Statements Invoking a synchronized instance method of an object acquires a lock on the object. When a lock is obtained on the object. Introduction to Java Programming. A synchronized statement can be used to acquire a lock on any object. The general form of a synchronized statement is as follows: synchronized (expr) { statements. not just this object. All rights reserved. } The expression expr must evaluate to an object reference. (c) 2005 Pearson Education. and then the lock is released. when executing a block of the code in a method.

All rights reserved. Suppose that the following is a synchronized instance method: public synchronized void xMethod() { // method body } This method is equivalent to public void xMethod() { synchronized (this) { // method body } } Liang. Sixth Edition. (c) 2005 Pearson Education. Inc.Synchronizing Statements vs. 0-13-148952-6 38 . Introduction to Java Programming. Methods Any synchronized instance method can be converted into a synchronized statement.

there is no particular access order.Lock +lock(): void +unlock(): void +newCondition(): Condition Acquires the lock.locks.locks. Otherwise.util. Sixth Edition. Introduction to Java Programming. The new locking features are flexible and give you more control for coordinating threads.ReentrantLock +ReentrantLock() +ReentrantLock(fair: boolean) Same as ReentrantLock(false). java. which can be used for thread communications. A lock is an instance of the Lock interface. Liang.concurrent. JDK 1. 0-13-148952-6 39 .Synchronization Using Locks A synchronized instance method implicitly acquires a lock on the instance before it executes the method. Creates a lock with the given fairness policy.5 enables you to use locks explicitly. «interface» java. (c) 2005 Pearson Education. All rights reserved. A lock may also use the newCondition() method to create any number of Condition objects. Inc.util. Returns a new Condition instance that is bound to this Lock instance. When the fairness is true. Releases the lock. as shown in Figure below.concurrent. which declares the methods for acquiring and releasing locks. the longest-waiting thread will get the lock.

You can create a lock with the specified fairness policy. Liang. False fairness policies grant a lock to a waiting thread without any access order. Sixth Edition.Fairness Policy ReentrantLock is a concrete implementation of Lock for creating mutual exclusive locks. Programs using fair locks accessed by many threads may have poor overall performance than those using the default setting. 0-13-148952-6 40 . Inc. but have smaller variances in times to obtain locks and guarantee lack of starvation. True fairness policies guarantee the longest-wait thread to obtain the lock first. Introduction to Java Programming. All rights reserved. (c) 2005 Pearson Education.

Sixth Edition. AccountWithSyncUsingLock Run Liang. Introduction to Java Programming.java in Listing 24.7 to synchronize the account modification using explicit locks. All rights reserved. Inc.Example: Using Locks This example revises AccountWithoutSync. 0-13-148952-6 41 . (c) 2005 Pearson Education.

0-13-148952-6 42 . A thread can specify what to do under a certain condition. Introduction to Java Programming. Liang. The signal() method wakes up one waiting thread. The await() method causes the current thread to wait until the condition is signaled. Conditions are objects created by invoking the newCondition() method on a Lock object. Inc. you can use its await(). Wakes up all waiting threads. as shown in Figure below. and signalAll() methods for thread communications. signal(). and the signalAll() method wakes all waiting threads. «interface» java. Sixth Edition. Wakes up one waiting thread.util.Cooperation Among Threads The conditions can be used to facilitate communications among threads. All rights reserved.concurrent. Once a condition is created. (c) 2005 Pearson Education.Condition +await(): void +signal(): void +signalAll(): Condition Causes the current thread to wait until the condition is signaled.

and the other withdraws from the same account. All rights reserved. If the amount is still not enough for a withdrawal. the second thread has to continue to wait for more fund in the account.Example: Thread Cooperation Write a program that demonstrates thread cooperation. Inc. Assume the initial balance is 0 and the amount to deposit and to withdraw is randomly generated. Whenever new fund is deposited to the account. The second thread has to wait if the amount to be withdrawn is more than the current balance in the account. ThreadCooperation Run Liang. one deposits to an account. Introduction to Java Programming. Suppose that you create and launch two threads. the first thread notifies the second thread to resume. (c) 2005 Pearson Education. Sixth Edition. 0-13-148952-6 43 .

lock. the withdraw task will wait for the newDeposit condition.lock(). lock. Withdraw Task lock.e. (c) 2005 Pearson Education. Deposit Task while (balance < withdrawAmount) newDeposit. use a lock with a condition: newDeposit (i.unlock().Cooperation Among Threads To synchronize the operations.. Inc.unlock(). the task signals the waiting withdraw task to try again.lock(). lock. All rights reserved. Liang. Sixth Edition. Introduction to Java Programming. The interaction between the two tasks is shown in Figure below. When the deposit task adds money to the account. 0-13-148952-6 44 . new deposit added to the account). balance -= withdrawAmount balance += depositAmount newDeposit. If the balance is less than the amount to be withdrawn.signalAll().await().

This is where condition object come in. so no other thread has a chance to make a deposit. Liang. All rights reserved. For example: Condition newDeposit = lock. But this thread has just gained exclusive access to the lock. A lock object can have one or more associated condition objects. (c) 2005 Pearson Education. JDK5. Sixth Edition. what do we do where there is not enough money in the account? We wait until some other thread has added funds. It is customary to give each condition object a name that evokes the condition that it represents. Inc.newCondition(). only to discover that it can¶t proceed until a condition is fulfilled. Introduction to Java Programming.Condition Object Often. For example.0 uses a condition object to manage threads that have acquired a lock but cannot do useful work. You obtain a condition object with the newCondition method. 0-13-148952-6 45 . a thread enters a critical section.

0-13-148952-6 46 . When another thread transfers money.signa(). or call newDeposit. to unblock all threads that are waiting for the condition. This lets in another thread that can (possibly) increase the account balance. it should call newDeposit. it calls newDeposit. At that time.signalAll(). As soon as the lock is available. All rights reserved. they are again runnable and the scheduler will eventually activate them again. Inc.Condition Object If the transfer method finds that sufficient funds are not available. When the threads are removed from the wait set. There is no guarantee that the condition is now fulfilled. returning from the await. one of them will acquire the lock and continue where it left off. they will attempt to reenter the object. (c) 2005 Pearson Education. Liang. chosen at random. The current thread is now blocked and gives up the lock.await(). Introduction to Java Programming. Sixth Edition. to unblock a single thread from the wait set. At this time the thread should test the condition again.

When a thread calls await. If none of them bother to unblock the waiting thread. 0-13-148952-6 47 . This can lead to deadlock situation. Sixth Edition.Condition Object It is crucial that some other thread calls the signalAll eventually. All rights reserved. Liang. Introduction to Java Programming. it has no way of unblocking itself. (c) 2005 Pearson Education. it will never run again. Inc. It puts its faith in the other thread.

signal(). To synchronize the operations. if the buffer is full.await(). Sixth Edition. buffer is not empty) and notFull (i. The buffer provides the method write(int) to add an int value to the buffer and the method read() to read and delete an int value from the buffer. 0-13-148952-6 48 .e. use a lock with two conditions: notEmpty (i. buffer is not full).Case Study: Producer/Consumer Consider the classic Consumer/Producer example. All rights reserved. if the buffer is empty. (c) 2005 Pearson Education. Introduction to Java Programming. The interaction between the two tasks is shown in Figure below.await(). Task for adding an int Task for deleting an int while (count == CAPACITY) notFull... Inc.e. The buffer size is limited. Liang. Add an int to the buffer Delete an int to the buffer notEmpty. When a task adds an int to the buffer.signal(). Suppose you use a buffer to store integers. the task will wait for the notEmpty condition. while (count == 0) notEmpty. notFull. the task will wait for the notFull condition. When a task deletes an int from the buffer.

Introduction to Java Programming. For simplicity. A lock must be acquired before a condition can be applied. All rights reserved. the buffer is implemented using a linked list (lines 4849). 0-13-148952-6 . (c) 2005 Pearson Education. The program contains the Buffer class (lines 43-89) and two tasks for repeatedly producing and consuming numbers to and from the buffer (lines 15-41). The write(int) method (line 58) adds an integer to the buffer.Case Study: Producer/Consumer (Optional) Listing 24. The conditions are bound to a lock.10 presents the complete program. ConsumerProducer Run 49 Liang. Sixth Edition. The read() method (line 75) deletes and returns an integer from the buffer. Two conditions notEmpty and notFull on the lock are created in lines 55-56. Inc.

Inc. (c) 2005 Pearson Education. 0-13-148952-6 50 . Introduction to Java Programming. All rights reserved.Deadlock The Dining-Philosophers¶ Problem Liang. Sixth Edition.

0-13-148952-6 51 . and neither can continue to run. Step 1 2 3 4 5 6 Thread 1 synchronized (object1) { Thread 2 synchronized (object2) { // do something here // do something here synchronized (object2) { // do something here } } } synchronized (object1) { // do something here } Wait for Thread 2 to release the lock on object2 Wait for Thread 1 to release the lock on object1 Liang. (c) 2005 Pearson Education. Now Thread 1 is waiting for the lock on object2 and Thread 2 for the lock on object1. Consider the scenario with two threads and two objects. Sixth Edition. as shown in Figure below. Thread 1 acquired a lock on object1 and Thread 2 acquired a lock on object2.Deadlock Sometimes two or more threads need to acquire the locks on several shared objects. in which each thread has the lock on one of the objects and is waiting for the lock on the other object. All rights reserved. The two threads wait for each other to release the in order to get the lock. This could cause deadlock. Introduction to Java Programming. Inc.

then on object2. you assign an order on all the objects whose locks must be acquired and ensure that each thread acquires the locks in that order. Liang. suppose the objects are ordered as object1 and object2. With this technique. Thread 2 must acquire a lock on object1 first. Introduction to Java Programming. 0-13-148952-6 52 . Thread 2 has to wait for a lock on object1. All rights reserved. So Thread 1 will be able to acquire a lock on object2 and no deadlock would occur. Using the resource ordering technique. For the example in Figure in last slide. Inc. Once Thread 1 acquired a lock on object1. Sixth Edition. (c) 2005 Pearson Education.Preventing Deadlock Deadlock can be easily avoided by using a simple technique known as resource ordering.

Sign up to vote on this title
UsefulNot useful