01-Multithreading Ver2 4spp
01-Multithreading Ver2 4spp
MultiThreading
Session objectives
Introduction
Creating thread
Thread class and Thread behaviors Thread properties
Thread pooling
Thread synchronization Deadlocks
By V Vn Hi Faculty of Information Technologies Industrial University of Ho Chi Minh City
Introduction
A program may consist of many tasks that can run concurrently. A thread is the flow of execution, from beginning to end, of a task. It provides the mechanism for running a task. With Java, you can launch multiple threads from a program concurrently. These threads can be executed simultaneously in multiprocessor systems
Introduction
In single-processor systems, the multiple threads share CPU time known as time sharing, and the operating system is
07/01/2013
Thread class
The Thread class contains the constructors for creating threads for tasks, and the methods for controlling threads.
3. Result
2. Start thread
07/01/2013
10
11
12
07/01/2013
Interrupting threads
There is no longer a way to force a thread to terminate. The interrupt() method can be used to request termination of a
thread.
Checking one thread is interrupted:
Thread.currentThread().isInterrupted()
If a thread is blocked, it cannot check the interrupted status. This is where the InterruptedException comes in.
13
14
Thread properties
16
07/01/2013
Managing threads:
Priorities (1)
Managing threads:
Priorities (2)
In Java, thread scheduler can use the thread priorities in the form of integer value to each of its thread to determine the
When a Java thread is created, it inherits its priority from the thread that created it. At any given time, when multiple threads are ready to be executed, the runtime
system chooses the runnable thread with the highest priority for execution.
In the implementation of threading scheduler usually applies one of the two following strategies:
Preemptive scheduling: If the new thread has a higher priority then current running thread leaves the runnable state and higher priority thread enter to the runnable state. Time-Sliced (Round-Robin) Scheduling: A running thread is allowed to be execute for the fixed time, after completion the time, current thread indicates to the another thread to enter it in the runnable state.
Managing threads:
Priorities (3)
Daemon threads
Two types of threads in Java:
1. User threads:
Created by the user Threads that work in the background providing service to other threads (e.g. the garbage collector thread)
2. Daemon threads:
When user thread exits, JVM checks to find out if any other thread is running.
If there are, it will schedule the next thread. If the only executing threads are daemon threads, it exits.
We can set a thread to be a Daemon if we do not want the main program to wait until a thread ends.
20
07/01/2013
Thread Pools
A thread pool is ideal to manage the number of tasks executing concurrently. Java provides the Executor interface for executing tasks in a thread pool and the ExecutorService interface for managing and controlling tasks
21
22
Executorsclass.
The newFixedThreadPool(int) method creates a fixed number of threads in a pool.
If a thread completes executing a task, it can be reused to execute
another task. If a thread terminates due to a failure prior to shutdown, a new thread will be created to replace it If all the threads in the pool are not idle and there are tasks waiting for execution.
23
for 60 seconds.
A cached pool is efficient for many short tasks.
24
07/01/2013
terminated
25 26
Thread Synchronization
What happens if two threads have access to the same object and each calls a method that modifies the state of the object? In such a case, data may become inconsistent. Situation is often called a race condition. To avoid simultaneous access of a shared object by multiple threads, you must learn how to synchronize the access.
Thread Synchronization
Thread Communication Without Synchronization
View follow example: UnsynchBankTest.java
There are some things wrong in this Bank. The Race Condition Explained:
The prolem is that these are not atomic operations. View follow
figure The real problem is that the work of the transfer method can be interrupted in the middle. If we could ensure that the method runs
to completion before the thread loses control, then the state of the
bank account object would not be corrupted.
27 28
07/01/2013
Thread Synchronization
Thread Synchronization
Synchronization is based on the concept of monitor.
A monitor is an object that is used as a mutually exclusive lock.
When one thread calls a synchronized method, it is guaranteed that the method will finish before another thread can execute any synchronized method on the same object.
31
32
07/01/2013
This mechanism ensures that there is a smooth transition of a particular resource between two competitive threads. It also oversees the condition in a program where one thread is:
Allowed to wait for the lock. Notified to end its waiting state and get the lock
When a thread executes a call to wait, it surrenders the object lock and enters a wait list for that object.
To remove a thread from the wait list, some other thread must make a call to notifyAll or notify, on the same object.
34
synchronized method.
33
notify()
notify() wakes up or notifies the first thread.
First thread
notifyAll()
notifyAll() wakes up or notifies all the threads that called wait( ) on the same object.
Thread 1
Thread 2
Thread 3
35
36
07/01/2013
If one thread calls a synchronized static method of a class, all synchronized static methods of the class are blocked until the first call returns. Example :
public static synchronized Singleton getInstance()
The basic outline for protecting a code block with a ReentrantLock is:
39
40
10
07/01/2013
This construct guarantees that only one thread at a time can enter the critical section.
Imagine we have a very simple case where we need to synchronize access to a pair of variables. One is a simple value
As soon as one thread locks the lock object, no other thread can
get past the lock statement. When other threads call lock, they are blocked until the first
41
Simple, but if we have a lot of contention or if we perform a lot of reads and few writes?
42
Using of ReadWriteLock
transfer:
if (bank.getBalance(from) >= amount)
// thread might be deactivated at this point
bank.transfer(from, to, amount); By the time the thread is running again, the account balance may have fallen below the withdrawal amount.
44
43
11
07/01/2013
You must make sure that the thread cannot be interrupted between the test and the insertion:
What do we do when there is not enough money in the account? We wait until some other thread has added funds. But this
45
46
If the Transfer method finds that sufficient funds are not available, it calls sufficientFunds.await(); =>The current thread is now blocked and gives up the lock. This
Instead, it stays blocked until another thread has called the signalAll
method on the same condition. The signalAll method call unblocks all threads that are waiting for the condition.
When the threads are removed from the wait set, they are again runnable
and the scheduler will eventually activate them again.
47 48
12
07/01/2013
A fair lock favors the thread that has been waiting for the longest time.
Fair locks are a lot slower than regular locks. You should only enable fair locking if you have a specific reason why fairness is essential for your problem.
49 50
Deadlocks
Analyzing following situation
13
07/01/2013
Deadlocks(cont.)
If all threads in an application are blocked. The system has deadlocked. Unfortunately, there is nothing in the Java programming language to avoid or break these deadlocks.
A Runnable encapsulates a task that runs asynchronously; you can think of it as an asynchronous method with no parameters and no return value. Drawback of Runnable:
Cannot return any type (of run method) No parameters (of run method)
So, we need another mechanic: Callable The Callable interface is a parameterized type, with a single method
call:
54
Future
object
holds
the
result
of
an
asynchronous
The FutureTask wrapper is a convenient mechanism for turning a Callable into both a Future and a Runnable it implements both interfaces.
computation. You use a Future object so that you can start a computation, give the result to someone, and forget about it. The owner of the Future object can obtain the result when it is ready.
55
56
14
07/01/2013
possible conflicts.
You can use the static methods, invokeLater and invokeAndWait in the javax.swing.SwingUtilities class to run the code in the
60
15
07/01/2013
61
62
Thread synchronization
63/27
16