Beruflich Dokumente
Kultur Dokumente
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
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
Threads Concept
Multiple threads on multiple CPUs
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
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
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
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
Thread States
A thread can be in one of Four states for threads: new, runnable, blocked, dead
sleep done sleeping suspend resume
blocked
new
start
await
signal
runnable
run exits stop
dead
Note: suspend , resume,stop deprecated. Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
Thread States
When a thread has just been created using the new operator, it is in the new state. Once start method is invoked (which calls the run method), the thread becomes runnable.
A runnable thread might not be running. There can be many runnable threads. But only one of them can be running at any time point. OS decides which thread to run. More on this later.
new
start
runnable
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
Thread States
2.
3. 4. 5.
The thread is currently running and method Thread.sleep is called suspend method of the thread is called. (deprecated) The thread calls the await method. The thread tries to lock an object locked by another thread. The thread calls an operation that is blocked on i/o.
sleep suspend await
blocked
runnable
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
Thread States
It has slept the specified amount of time. resume method of the thread is called. (deprecated) Another method calls signal or signalAll Object lock released by other thread I/O completed.
done sleeping
blocked
resume signal
runnable
Lock available I/O complete
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
10
Thread States
Its run method exits. Natural death. stop method of the thread is called. (deprecated) An exception is thrown but not caught.
runnable
run exits stop
dead
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
11
Thread States
Finding
Method isAlive allows you to find out whether a thread is alive or dead.
This
method returns true if the thread is runnable or blocked, false if the thread is still new and not yet runnable or if the thread is dead
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
12
Every time a number is printed, the print100 thread is yielded. So, the numbers are printed after the characters.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
13
Every time a number (>= 50) is printed, the print100 thread is put to sleep for 1 millisecond.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
14
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
15
public void run(){ Thread thread4 = new Thread(new PrintChar('c', 60)); thread4.start(); try { for (int i = 1; i < lastNum; i++){ System.out.print(" " + i); if (i == 50) thread4.join(); } } catch (InterruptedException ex) { } }
The numbers after 50 are printed after thread4 is finished.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
16
17
Outline
Introduction:
Uses
18
Thread Scheduling
At any time, there might be many runnable threads. But only one of them is actually running. The thread scheduler decides which runnable thread to run. 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, or It ceases to be runnable (dead or blocked), 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, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
19
Thread Scheduling
Native thread implementation (e.g. Windows): Performs time-slicing. Interrupts the running thread periodically to give other threads a chance to run. Green thread implementation (e.g. Solaris) Does not perform time-slicing. It keeps a running thread active until a higher-priority thread awakes and takes control.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
20
Thread Scheduling
The answer on slide 19 is precise for the green thread implementation. For the native thread implementation, the precise answer is A running Java thread will continue to run until It calls yield method, or It ceases to be runnable (dead or blocked), or Another thread with higher priority moves out of blocked state, or It is pre-emptied by OS (time-slicing). Then the thread scheduler kicks in and picks another thread with the highest priority to run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
21
Thread Priority
Each thread is assigned a default priority of Thread.NORM_PRIORITY. You can reset the priority using setPriority(int priority). Some constants for priorities include
Thread.MIN_PRIORITY Thread.MAX_PRIORITY Thread.NORM_PRIORITY
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
22
FlashingText
Run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
23
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
24
25
} }); }
EventDispatcherThreadDemo
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
Run
26
The example creates an applet that displays a running clock and announces the time at one-minute intervals. For example, if the current time is 6:30:00, the applet announces, "six oclock thirty minutes a.m." If the current time is 20:20:00, the applet announces, "eight oclock twenty minutes p.m." Also add a label to display the digital time. ClockWithAudio Run
27
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
ClockWithAudioOnSeparateThread
Run
28
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
Thread Pools
Starting a new thread for each task could limit throughput and cause poor performance. A thread pool is ideal to manage the number of tasks executing concurrently. JDK 1.5 uses the Executor interface for executing tasks in a thread pool and the ExecutorService interface for managing and controlling tasks. ExecutorService is a subinterface of Executor.
interface
java.util.concurrent.Executor
+execute(Runnable object): void Executes the runnable task.
\ interface
java.util.concurrent.ExecutorService
+shutdown(): void +shutdownNow(): List<Runnable> Shuts down the executor, but allows the tasks in the executor to complete. Once shutdown, it cannot accept new tasks. Shuts down the executor immediately even though there are unfinished threads in the pool. Returns a list of unfinished tasks. Returns true if the executor has been shutdown. Returns true if all tasks in the pool are terminated.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
29
Creating Executors
To create an Executor object, use the static methods in the Executors class.
java.util.concurrent.Executors
+newFixedThreadPool(numberOfThreads: Creates a thread pool with a fixed number of threads executing int): ExecutorService concurrently. A thread may be reused to execute another task after its current task is finished. +newCachedThreadPool(): Creates a thread pool that creates new threads as needed, but ExecutorService will reuse previously constructed threads when they are available.
ExecutorDemo
Run
30
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
Thread Synchronization
A shared resource may be corrupted if it is accessed simultaneously by multiple threads. For example, two unsynchronized threads accessing the same bank account may cause conflict.
Step 1 2 3 4 balance 0 0 1 1 thread[i]
newBalance = bank.getBalance() + 1; newBalance = bank.getBalance() + 1; bank.setBalance(newBalance); bank.setBalance(newBalance);
thread[j]
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
31
Objective: Write a program that demonstrates the problem of resource conflict. Suppose that you create and launch one hundred threads, each of which adds a penny to an account. Assume that the account is initially empty.
java.lang.Runnable
-char token
100 1 1 1
AccountWithoutSync
-bank: Account -thread: Thread[]
Account
-balance: int +getBalance(): int +deposit(amount: int): void
AccountWithoutSync Run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
32
Race Condition
What, then, caused the error in the example? Here is a possible scenario:
Step 1 2 3 4
);
balance 0 0 1 1
Task 1
newBalance = balance + 1;
Task 2
The effect of this scenario is that Task 1 did nothing, because in Step 4 Task 2 overrides Task 1's result. Obviously, the problem is that Task 1 and Task 2 are accessing a common resource in a way that causes conflict. This is a common problem known as a race condition in multithreaded programs. 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. As demonstrated in the preceding example, the Account class is not thread-safe.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
33
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
34
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
35
Task 2
-char token +getToken +setToken +paintComponet +mouseClicked
+getToken Execute the deposit method +setToken +paintComponet -char token +mouseClicked +getToken Release the lock +setToken +paintComponet
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
36
Synchronizing Statements
Invoking a synchronized instance method of an object acquires a lock on the object, and invoking a synchronized static method of a class acquires a lock on the class. A synchronized statement can be used to acquire a lock on any object, not just this object, when executing a block of the code in a method. This block is referred to as a synchronized block. The general form of a synchronized statement is as follows:
synchronized (expr) { statements; }
The expression expr must evaluate to an object reference. If the object is already locked by another thread, the thread is blocked until the lock is released. When a lock is obtained on the object, the statements in the synchronized block are executed, and then the lock is released.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
37
38
java.util.concurrent.locks.ReentrantLock
+ReentrantLock() +ReentrantLock(fair: boolean) Same as ReentrantLock(false). Creates a lock with the given fairness policy. When the fairness is true, the longest-waiting thread will get the lock. Otherwise, there is no particular access order.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
39
Fairness Policy
ReentrantLock is a concrete implementation of Lock for creating mutual exclusive locks. You can create a lock with the specified fairness policy. True fairness policies guarantee the longest-wait thread to obtain the lock first. False fairness policies grant a lock to a waiting thread without any access order. Programs using fair locks accessed by many threads may have poor overall performance than those using the default setting, but have smaller variances in times to obtain locks and guarantee lack of starvation.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
40
AccountWithSyncUsingLock
Run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
41
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
42
ThreadCooperation
Run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
43
lock.lock();
+getToken +setToken -char token +paintComponet while (balance < withdrawAmount) +mouseClicked +getToken newDeposit.await(); +setToken +paintComponet +mouseClicked
balance -= withdrawAmount
-char token
lock.unlock();
+getToken +setToken
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
44
Condition Object
Often, a thread enters a critical section, only to discover that it cant proceed until a condition is fulfilled. JDK5.0 uses a condition object to manage threads that have acquired a lock but cannot do useful work. For example, what do we do where there is not enough money in the account? We wait until some other thread has added funds. But this thread has just gained exclusive access to the lock, so no other thread has a chance to make a deposit. This is where condition object come in. A lock object can have one or more associated condition objects. You obtain a condition object with the newCondition method. It is customary to give each condition object a name that evokes the condition that it represents. For example: Condition newDeposit = lock.newCondition();
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
45
Condition Object
If the transfer method finds that sufficient funds are not available, it calls newDeposit.await(); The current thread is now blocked and gives up the lock. This lets in another thread that can (possibly) increase the account balance. When another thread transfers money, it should call newDeposit.signalAll(); to unblock all threads that are waiting for the condition. or call newDeposit.signa(); to unblock a single thread from the wait set, chosen at random. When the threads are removed from the wait set, they are again runnable and the scheduler will eventually activate them again. At that time, they will attempt to reenter the object. As soon as the lock is available, one of them will acquire the lock and continue where it left off, returning from the await. At this time the thread should test the condition again. There is no guarantee that the condition is now fulfilled.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
46
Condition Object
It is crucial that some other thread calls the signalAll eventually. When a thread calls await, it has no way of unblocking itself. It puts its faith in the other thread. If none of them bother to unblock the waiting thread, it will never run again. This can lead to deadlock situation.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
47
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
48
ConsumerProducer
Run
49
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
50
Deadlock
Sometimes two or more threads need to acquire the locks on several shared objects. This could cause deadlock, in which each thread has the lock on one of the objects and is waiting for the lock on the other object. Consider the scenario with two threads and two objects, as shown in Figure below. Thread 1 acquired a lock on object1 and Thread 2 acquired a lock on object2. Now Thread 1 is waiting for the lock on object2 and Thread 2 for the lock on object1. The two threads wait for each other to release the in order to get the lock, 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 }
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
51
Preventing Deadlock
Deadlock can be easily avoided by using a simple technique known as resource ordering. With this technique, you assign an order on all the objects whose locks must be acquired and ensure that each thread acquires the locks in that order. For the example in Figure in last slide, suppose the objects are ordered as object1 and object2. Using the resource ordering technique, Thread 2 must acquire a lock on object1 first, then on object2. Once Thread 1 acquired a lock on object1, Thread 2 has to wait for a lock on object1. So Thread 1 will be able to acquire a lock on object2 and no deadlock would occur.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6
52