Muhammad Multithreading
Muhammad Multithreading
Thread
Thread: single sequential flow of control within a
program
Single-threaded program can handle one task at any
time.
Multitasking allows single processor to run several
concurrent threads.
Most modern operating systems support multitasking.
Threads Concept
Multiple
threads on
multiple
CPUs
Multiple
threads
sharing a
single CPU
Thread 1
Thread 2
Thread 3
T hread 1
T hread 2
T hread 3
Threads in Java
Creating threads in Java:
Extend java.lang.Thread class
OR
Implement java.lang.Runnable interface
Threads in Java
Creating threads in Java:
Extend java.lang.Thread class
run() method must be overridden (similar to main method of
sequential program)
run() is called when execution of the thread begins
A thread terminates when run() returns
start() method invokes run()
Calling run() does not create a new thread
Threads in Java
Creating threads in Java:
Extend java.lang.Thread class
Implement java.lang.Runnable interface
Single method: public void run()
Thread class implements Runnable.
Thread termination
A thread becomes Not Runnable when one of these
events occurs:
Its sleep method is invoked.
The thread calls the wait method to wait for a specific
condition to be satisifed.
The thread is blocking on I/O.
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();
...
}
...
}
+Thread(task: Runnable)
+start(): void
+isAlive(): boolean
Starts the thread that causes the run() method to be invoked by the JVM.
Tests whether the thread is currently running.
+join(): void
+yield(): void
Causes this thread to temporarily pause and allow other threads to execute.
+interrupt(): void
10
Every time a number (>= 50) is printed, the print100 thread is put to sleep for 1 millisecond.
11
Thread States
A thread can be in one of five states:
New, Ready, Running, Blocked, or
Finished.
yield(), or
time out
Thread created
start()
New
Ready
Target
finished
Running
run()
run() returns
join()
interrupt()
Finished
sleep()
wait()
Wait for time
out
Wait to be
notified
Time out
notify() or
notifyAll()
Blocked
Interrupted()
13
Thread methods
isAlive()
method used to find out the state of a thread.
returns true: thread is in the Ready, Blocked, or
Running state
returns false: thread is new and has not started
or if it is finished.
interrupt()
f a thread is currently in the Ready or Running
state, its interrupted flag is set; if a thread is
currently blocked, it is awakened and enters the
Ready state, and an java.io.InterruptedException
is thrown.
The isInterrupt() method tests whether the thread
is interrupted.
14
15
Thread Priority
Each thread is assigned a default priority
of Thread.NORM_PRIORITY (constant of 5).
You can reset the priority using
setPriority(int priority).
Some constants for priorities include
Thread.MIN_PRIORITY Thread.MAX_PRIORITY
Thread.NORM_PRIORITY
By default, a thread has the priority level of
the thread that created it.
16
Thread Scheduling
An operating systems thread scheduler
determines which thread runs next.
Most operating systems use timeslicing for
threads of equal priority.
Preemptive scheduling: when a thread of
higher priority enters the running state, it
preempts the current thread.
Starvation: Higher-priority threads can
postpone (possible forever) the execution
of lower-priority threads.
17
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.
Executor interface for executing Runnable objects in a thread pool
ExecutorService is a subinterface of Executor.
interface
java.util.concurrent.Executor
+execute(Runnable object): void
\
interface
java.util.concurrent.ExecutorService
+shutdown(): void
Shuts down the executor, but allows the tasks in the executor to
complete. Once shutdown, it cannot accept new tasks.
+shutdownNow(): List<Runnable>
+isShutdown(): boolean
+isTerminated(): boolean
18
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.
19
Thread Synchronization
balance
thread[i]
1
2
3
4
0
0
1
1
newBalance = bank.getBalance() + 1;
thread[j]
newBalance = bank.getBalance() + 1;
bank.setBalance(newBalance);
bank.setBalance(newBalance);
20
Race Condition
What, then, caused the error in the example? Here is a possible
scenario:
Step
balance
Task 1
1
2
3
4
0
0
1
1
newBalance = balance + 1;
Task 2
newBalance = balance + 1;
balance = newBalance;
balance = newBalance;
);
Effect: Task 1 did nothing (in Step 4 Task 2 overrides the result)
Problem: Task 1 and Task 2 are accessing a common resource in a way
that causes conflict.
Known as a race condition in multithreaded programs.
A thread-safe class does not cause a race condition in the presence of
multiple threads.
21
synchronized
Problem: race conditions
Solution: give exclusive access to one thread at a time
to code that manipulates a shared object.
Synchronization keeps other threads waiting until the
object is available.
The synchronized keyword synchronizes the method so
that only one thread can access the method at a time.
22
Task 2
-char token
+getToken
+setToken
+paintComponet
+mouseClicked
+getToken
Execute the deposit method
+setToken
+paintComponet
-char
token
+mouseClicked
+getToken
Release the lock
+setToken
+paintComponet
24
Synchronizing Statements
Invoking a synchronized instance method of an object
acquires a lock on the object.
Invoking a synchronized static method of a class acquires
a lock on the class.
A synchronized block can be used to acquire a lock on any
object, not just this object, when executing a block of code.
synchronized (expr) {
statements;
}
26
Synchronization
Using Locks
+unlock(): void
+newCondition(): Condition
java.util.concurrent.locks.ReentrantLock
+ReentrantLock()
Same as ReentrantLock(false).
+ReentrantLock(fair: boolean)
27
Fairness
Policy
ReentrantLock:concrete implementation of
Lock for creating mutually exclusive locks.
Create a lock with the specified fairness policy.
True fairness policies guarantee the longestwait thread to obtain the lock first.
False fairness policies grant a lock to a waiting
thread without any access order.
28
interface
java.util.concurrent.Condition
+await(): void
+signal(): void
+signalAll(): Condition
29
Withdraw Task
-char token
-char token
+getToken
+setToken
-char token
+paintComponet
while
(balance < withdrawAmount)
+mouseClicked
+getToken
newDeposit.await();
+setToken
+paintComponet
+mouseClicked
+getToken
+setToken
-char token
+paintComponet
balance += depositAmount
+mouseClicked
+getToken
+setToken
+paintComponet
-char
token
newDeposit.signalAll();
+mouseClicked
lock.lock();
balance -= withdrawAmount
-char token
lock.unlock();
+getToken
+setToken
lock.lock();
+getToken
+setToken
lock.unlock();
+paintComponet
+mouseClicked
-char token
30
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.
In the figure below, the two threads wait for each other to release
the in order to get a lock, and neither can continue to run.
Step
1
2
3
4
5
6
Thread 2
Thread 1
synchronized(object1){
//dosomethinghere
synchronized(object2){
//dosomethinghere
}
}
synchronized(object2){
//dosomethinghere
synchronized(object1){
//dosomethinghere
}
}
32
Preventing Deadlock
33