Chapter 2 - Multithreading - PPTX (Autosaved)
Chapter 2 - Multithreading - PPTX (Autosaved)
Multithreading
Computer Science and Engineering Department@SoEEC
Advanced Programming(CSE 3312)
Key Objectives:
to:
o Understand what multi-threaded programs are
(if available) so that multiple tasks execute concurrently and the application can
operate more efficiently.
Multithreading can also increase performance on single-processor systems that
may create threads for performing housekeeping tasks such as garbage collection
.....What are Threads
As shown in the above figure, thread is executed inside the process. There is context-
switching between the threads. There can be multiple processes inside the OS and one
process can have multiple threads.
3. Multi-threading
• Multi-threading in java is a process of executing multiple threads
simultaneously.
Thread is basically a lightweight sub-process, a smallest unit of processing.
common memory area. They don't allocate separate memory area so saves
memory, and context-switching between the threads takes less time than
process(see figure above).
Java Multithreading is mostly used in games, animation etc.
3.1 Why
Multithreading ?
To maintain responsiveness of an application
during a long running task.
To enable cancellation of separable tasks.
New
start
ir es/
p
l Ex I/ O
a Ready
n terv yAll Inte Comp
i f l
le ep /noti Loc rrupt/ etes/
s ify ll Time slice ka
t A dispatched cq u
no it fy expires ired
y / no
tif Iss u
e
no Running Ente IO requ
r e
wait state synchr st/
men oniz
t ed
ait
p/w
Blocked
e
Task
Sle
Waiting completes
Sleeping
Terminated
5. Creating and Executing
Threads
To implement multithreading, Java defines two ways by which
a thread can be created.
1. Implementing the Runnable interface
Runnable
represents a “task” that can be executed concurrently with other tasks
declares method run in which you place the code that defines the task to
perform.
Define a class that implements Runnable
class Task implements Runnable{
public void run(){//define the task here}
}
Instantiate the Thread class
invoke Thread constructor with an instance of this Runnable class
Then, call start method of the Thread instance
public static void main(String [] args){
Thread t = new Thread(new Task());
t.start(); }
Example
5. Creating and Executing
Threads
2. By Extending Thread class
Define a subclass of java.lang.Thread
In another thread (e.g., the main), create an instance of the Thread subclass
t.start(); }
Example
6. The Thread Class
Constructors
Thread( threadName )
Thread()
Creates an auto numbered Thread of format Thread-1, Thread-2...
Methods
void run()
"Does work" of thread
Can be overridden in a subclass of Thread
start
Launches thread, then returns to caller
Calls run
Error to call start twice for same thread(IllegalThreadStateException)
static sleep( milliseconds )
Thread sleeps for number of milliseconds
Can give lower priority threads a chance to run
….Thread Class
interrupt)()
Interrupts a thread
static interrupted()
Returns true if current thread interrupted
isInterrupted()
Determines if a thread is interrupted
isAlive()
Returns true if start has been called and not dead (run function has not
completed)
yield ()
Cause the currently running thread to temporarily pause and allows
other threads to execute.
setName(threadName)
Set name of the thread
getName()
Returns the name of the thread.
….Thread Class
toString()
Returns thread name, priority, and ThreadGroup
Join()
Wait for a thread to end
InterruptedException
public static void sleep(long miliseconds, int
nanos)throws InterruptedException
Sleep method in java
Example:
Thread Priorities and Thread
Scheduling
Every Java thread has a thread priority that helps the operating system
5)
In most cases, thread scheduler schedules the threads according to their
Like main, the run method defines a starting point for the JVM
The thread’s run() method must finish and return for the thread to stop
The code in method main executes in the main thread, a thread created by the
JVM
A program will not terminate until its last thread completes execution
7. Thread Pools
Java Thread pool represents a group of worker threads that are waiting for the job and reuse
many times.
In case of thread pool, a group of fixed size threads are created. A thread from the thread pool is
pulled out and assigned a job by the service provider. After completion of the job, thread is
contained in the thread pool again.
Executor interface :- to manage the execution of Runnable objects
new thread.
Executor method execute() accepts a Runnable as an argument
Assigns each Runnable it receives to one of the available threads in the thread pool
If none available, creates a new thread or waits for a thread to become available
7.1 Thread Pools
Interface java.util.concurrent.ExecutorService
extends Executor
java.util.concurrent.Executors
methods
shutdown() notifies the ExecutorService to stop accepting new tasks, but continues
……
es.execute(new Task());
es.execute(new Task());
ThreadPoolDemo
8. Thread Synchronization
by multiple threads.
….Thread Synchronization
Mutual exclusion
thread must acquire the lock before it can proceed with its operation
lock will be blocked until the first thread releases the lock
…. Thread Synchronization
synchronized statement
synchronized ( object ){
statements
} // end synchronized statement
where object is the object whose monitor lock will be
1) Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
1) by synchronized method
2) by synchronized block
Concept of Lock
Synchronization is built around an internal entity known as the lock or monitor. Every
object has an lock associated with it. By convention, a thread that needs consistent
access to an object's fields has to acquire the object's lock before accessing them, and
then release the lock when it's done with them.
From Java package, java.util.concurrent.locks contains several lock implementations.
Mutual Exclusive
i) Synchronized method
If you declare any method as synchronized, it is
known as synchronized method.
Synchronized method is used to lock an object for
any shared resource.
When a thread invokes a synchronized method, it
automatically acquires the lock for that object and
releases it when the thread completes its task.
Syntax:
Example
Mutual Exclusive
resource of the method. Suppose you have 50 lines of code in your method,
but you want to synchronize only 5 lines, you can use synchronized block.
If you put all the codes of the method in the synchronized block, it will work
Example
Inter-thread communication
Inter-thread communication or Co-operation is all about allowing
running in its critical section and another thread is allowed to enter (or lock)
in the same critical section to be executed.
class:
1) wait()
2) notify()
3) notifyAll()
Inter-thread communication
1) wait() method
Causes current thread to release the lock and wait until either another thread
invokes the notify() method or the notifyAll() method for this object, or a
specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from
Example1 Example2
Inter-thread communication
The process of inter-thread communication
Deadlock