chapter 9 (horstmann’s book) multithreading hwajung lee
TRANSCRIPT
![Page 1: Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee](https://reader031.vdocuments.us/reader031/viewer/2022022206/621367421b0b58552768111c/html5/thumbnails/1.jpg)
Chapter 9 (Horstmann’s Book)Multithreading
Hwajung Lee
![Page 2: Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee](https://reader031.vdocuments.us/reader031/viewer/2022022206/621367421b0b58552768111c/html5/thumbnails/2.jpg)
Thread Basics Thread Synchronization
![Page 3: Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee](https://reader031.vdocuments.us/reader031/viewer/2022022206/621367421b0b58552768111c/html5/thumbnails/3.jpg)
Thread: program unit that is executed independently Multiple Threads: Program units what can be executed in
parallel. Multiple threads run simultaneously.
When executes
▪ Multiprocessor computers: threads actually run in parallel
OR
▪ Illusion of threads running in parallel.
▪ That is, Virtual machine executes each thread for short time slice. Thread scheduler activates, deactivates threads.
![Page 4: Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee](https://reader031.vdocuments.us/reader031/viewer/2022022206/621367421b0b58552768111c/html5/thumbnails/4.jpg)
How to implement Running Threads
Define class that implements Runnable interface. Runnable has one method.
void run()
Place thread action into run() method
Construct an object of the class which implements the Runnable Interface
Construct an object of Thread class
start() thread
![Page 5: Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee](https://reader031.vdocuments.us/reader031/viewer/2022022206/621367421b0b58552768111c/html5/thumbnails/5.jpg)
public class MyRunnable implements Runnable{
public void run(){
thread action}
} ... Runnable r = new MyRunnable(); Thread t = new Thread(r); t.start();
![Page 6: Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee](https://reader031.vdocuments.us/reader031/viewer/2022022206/621367421b0b58552768111c/html5/thumbnails/6.jpg)
Run two threads in parallel Each thread
prints 10 greetings
for (int i = 1; i <= 10; i++){
System.out.println(i + ": " + greeting);Thread.sleep(100);
}
After each printout, sleep for 100 milliseconds All threads should occasionally yield control sleep() throws InterruptedException
![Page 7: Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee](https://reader031.vdocuments.us/reader031/viewer/2022022206/621367421b0b58552768111c/html5/thumbnails/7.jpg)
Ch9/greeting/GreetingProducer.java Ch9/greeting/ThreadTester.java
![Page 8: Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee](https://reader031.vdocuments.us/reader031/viewer/2022022206/621367421b0b58552768111c/html5/thumbnails/8.jpg)
Sample Output (Note: output not exactly interleaved.)
1: Hello, World! 1: Goodbye, World! 2: Hello, World! 2: Goodbye, World! 3: Hello, World! 3: Goodbye, World! 4: Hello, World! 4: Goodbye, World! 5: Hello, World! 5: Goodbye, World! 6: Hello, World! 6: Goodbye, World! 7: Hello, World! 7: Goodbye, World! 8: Goodbye, World! 8: Hello, World! 9: Goodbye, World! 9: Hello, World! 10: Goodbye, World! 10: Hello, World!
☞The thread scheduler gives no guarantee about the order in which threads are executed. Moreover, there will always be slight variations in running times, especially when calling operating system services (such as input and output). Thus, you should expect that the order in which each thread gains control appears to be somewhat random.
![Page 9: Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee](https://reader031.vdocuments.us/reader031/viewer/2022022206/621367421b0b58552768111c/html5/thumbnails/9.jpg)
![Page 10: Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee](https://reader031.vdocuments.us/reader031/viewer/2022022206/621367421b0b58552768111c/html5/thumbnails/10.jpg)
Each thread has thread state
priority
Thread states: new
▪ before start() called
runnable
blocked
dead
▪ after run() method exits
![Page 11: Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee](https://reader031.vdocuments.us/reader031/viewer/2022022206/621367421b0b58552768111c/html5/thumbnails/11.jpg)
Reasons for entering the blocked state:
Sleeping
Waiting for I/O
Waiting to acquire lock (later)
Waiting for condition (later)
Unblocks only if the reason for the blocking goes away
![Page 12: Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee](https://reader031.vdocuments.us/reader031/viewer/2022022206/621367421b0b58552768111c/html5/thumbnails/12.jpg)
Scheduler activates a new (next) thread if a thread has completed its time slice a thread has blocked itself a thread with higher priority has become runnable
Scheduler determines a new thread to run by looking only at all runnable threads, and picking one with the highest priority value. (The priority values are
system-dependant and not adjustable by an application programmer.)OR Picking one at random or using a round-robin scheme to gives each
thread a chance.
![Page 13: Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee](https://reader031.vdocuments.us/reader031/viewer/2022022206/621367421b0b58552768111c/html5/thumbnails/13.jpg)
Normal way to terminate a thread
Thread terminates when run() exits
However, you sometimes need to terminate running thread (Ex) you may have several threads attempting to find a solution to a
problem. As soon as the first one has succeeded, you can terminate the other ones.
![Page 14: Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee](https://reader031.vdocuments.us/reader031/viewer/2022022206/621367421b0b58552768111c/html5/thumbnails/14.jpg)
Example
Two producers, one consumer
Each producer thread inserts 100 greetings into the same queue.
Each consumer thread removes all of the greetings in the queue.
![Page 15: Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee](https://reader031.vdocuments.us/reader031/viewer/2022022206/621367421b0b58552768111c/html5/thumbnails/15.jpg)
In the try{ } blockint i = 1; while (i <= greetingCount) {
if (!queue.isFull()) {
queue.add(i + ": " + greeting); i++;
} Thread.sleep((int)(Math.random() * DELAY));
}
![Page 16: Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee](https://reader031.vdocuments.us/reader031/viewer/2022022206/621367421b0b58552768111c/html5/thumbnails/16.jpg)
In the try{ } blockint i = 1; while (i <= greetingCount) {
if (!queue.isEmpty()) {
Object greeting = queue.remove(); System.out.println(greeting); i++;
} Thread.sleep((int)(Math.random() * DELAY));
}
![Page 17: Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee](https://reader031.vdocuments.us/reader031/viewer/2022022206/621367421b0b58552768111c/html5/thumbnails/17.jpg)
1: Hello, World!
1: Goodbye, World! 2: Hello, World! 3: Hello, World! ... 99: Goodbye, World! 100: Goodbye, World!
![Page 18: Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee](https://reader031.vdocuments.us/reader031/viewer/2022022206/621367421b0b58552768111c/html5/thumbnails/18.jpg)
Sometimes, the program will corrupt the queue and not work correctly. The consumer thread gets stuck and won’t complete. Even though 200
greetings were inserted in the queue, it can’t retrieve them all. It may complete, but print the same greetings repeatedly.
Can you spot the problem? Can see problem better when turning debugging on
queue.setDebug(true); Ch9/queue1/ThreadTester.java Ch9/queue1/Producer.java Ch9/queue1/Consumer.java Ch9/queue1/BoundedQueue.java
![Page 19: Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee](https://reader031.vdocuments.us/reader031/viewer/2022022206/621367421b0b58552768111c/html5/thumbnails/19.jpg)
Race Condition occurs if the effect of multiple threads on shared data depends on the order in which the threads are scheduled.
Multiple threads, in their race to complete their respective task, rush to win the race.
![Page 20: Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee](https://reader031.vdocuments.us/reader031/viewer/2022022206/621367421b0b58552768111c/html5/thumbnails/20.jpg)
Race Condition Scenario
First thread calls add and executes
elements[tail] = anObject;
First thread at end of time slice
Second thread calls add and executes
elements[tail] = anObject;
tail++;
Second thread at end of time slice
First thread executestail++;
![Page 21: Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee](https://reader031.vdocuments.us/reader031/viewer/2022022206/621367421b0b58552768111c/html5/thumbnails/21.jpg)
To fix the race conditions, you need to ensure that only one thread manipulates the queue at any given moment.
![Page 22: Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee](https://reader031.vdocuments.us/reader031/viewer/2022022206/621367421b0b58552768111c/html5/thumbnails/22.jpg)
Locking Mechanism Thread can temporarily acquire ownership of a lock
When another thread tries to acquire same lock, it is blocked.
When first thread releases the lock, other threads are unblocked and try again
Two kinds of locks Objects of ReentrantLock class or another class implementing
java.util.concurrent.Lock interface type in java.util.concurrent.locks packageLocks
Locks that are built into every Java object
![Page 23: Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee](https://reader031.vdocuments.us/reader031/viewer/2022022206/621367421b0b58552768111c/html5/thumbnails/23.jpg)
aLock = new ReentrantLock();. . .aLock.lock();try{
protected code}finally{
aLock.unlock();} ☞ The finally clause ensures that the lock is
unlocked even when an exception is thrown in the protected code.
![Page 24: Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee](https://reader031.vdocuments.us/reader031/viewer/2022022206/621367421b0b58552768111c/html5/thumbnails/24.jpg)
A deadlock occurs if no thread can proceed because each thread is waiting for another to do some work first.
![Page 25: Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee](https://reader031.vdocuments.us/reader031/viewer/2022022206/621367421b0b58552768111c/html5/thumbnails/25.jpg)
Object = phone booth Thread = person Locked object = closed booth Blocked thread = person waiting for
booth to open