1
2
We can walk, talk, breathe, see, hear, smell... all at the same
time
Computers can do this as well - download a file, print a file,
receive email, run the clock
Only computers that have multiple processors can truly execute
multiple instructions concurrently
Operating systems on single-processor computers create the
illusion of concurrent execution by rapidly switching between
activities, but on such computers only a single instruction can
execute at once.
Java makes concurrency available to you through the language
and APIs.
3
A thread is a control/flow/path of execution that exists within a process.
Thread is portion of a program that can execute concurrently with other threads.
Each thread is a statically ordered sequence of instructions.
Sequential flow of control within a program
Threads are being extensively used to express concurrency on both single and
multiprocessors machines.
Sharing a single CPU between multiple tasks (or "threads") in a way designed to
minimize the time required to switch tasks.
accomplished by sharing as much as possible of the program execution environment
between the different tasks.
Programming a task having multiple threads of control is called
Multithreading or Multithreaded Programming.
A multithreaded application contains separate threads of execution, where each
thread
o Has its own method-call stack and program counter
4
o execute concurrently with other threads.
o shares application-wide resources such as memory with other threads.
In single-threaded applications lengthy activities must complete before others can begin
which leads to poor responsiveness.
In a multithreaded application, threads can be distributed across multiple processors (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 simulate
concurrency—when one thread cannot proceed (because, for example, it is waiting for the
result of an I/O operation), another can use the processor.
The Java Virtual Machine (JVM) creates threads to run a program, the JVM also may create
threads for performing housekeeping tasks such as garbage collection
5
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.
6
• Multi-threading in java is a process of executing multiple threads
simultaneously.
Thread is basically a lightweight sub-process, a smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
But we use multithreading than multiprocessing because threads share a
common memory area. They don't allocate separate memory area so saves
memory, and context-switching between the threads takes less time than
process.
Java Multithreading is mostly used in games, animation etc.
7
To maintain responsiveness of an application during a long
running task.
To enable cancellation of separable tasks.
Some problems are intrinsically parallel.
To monitor status of some resource (DB).
Some APIs and systems demand it: Swing.
To take advantage of multiple processors.
To perform multiple operations at the same time.
8
• A thread can be in one of the five states. According to sun,
there is only 4 states in thread life cycle in java new,
runnable, non-runnable and terminated.
But for better understanding the threads, we are
explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM.
The java thread states are as follows:
1. New
2. Runnable(Ready)
3. Running
4. Non-Runnable (Blocked)
9
5. Dead (Terminated)
1) New State:- The thread is in new state if you create an
instance of Thread class but before the invocation of start()
method.
2) Ready (Runnable) State:-The thread is in runnable state
after invocation of start() method, but the thread scheduler
has not selected it to be the running thread.
3) Running State:- The thread is in running state if the thread
scheduler has selected it.
4) Non-Runnable (Blocked) State:-This is the state when
the thread is still alive, but is currently not eligible to run.
5) Dead (Terminated) State:-A thread is in terminated or
dead state when its run() method exits.
10
11
Two techniques to create threads in java
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();
12 }
Example: By implementing the Runnable interface:
13
2. By Extending Thread class
Define a subclass of java.lang.Thread
Define a run method
class Task extends Thread{
public void run(){define the task here}
In another thread (e.g., the main), create an instance of the Thread subclass
Then, call start method of that instance
public static void main(String [] args){
Task t = new Task();
t.start();
}
14
Example: By extending Thread Class
15
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
static sleep( milliseconds )
Thread sleeps for number of milliseconds
Can give lower priority threads a chance to run
16
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.
17
toString
Returns thread name, priority, and ThreadGroup
join
Calling thread waits for thread receiving message
to die before it can proceed
No argument or 0 millisecond argument means
thread will wait indefinitely
-Can lead to deadlock
18
Thread scheduler in java is the part of the JVM that decides
which thread should run.
There is no guarantee that which runnable thread will be
chosen to run by the thread scheduler. Only one thread at a
time can run in a single process.
The thread scheduler mainly uses preemptive or time slicing
scheduling to schedule the threads.
19
The sleep() method of Thread class is used to sleep a thread for
the specified amount of time.
Syntax of sleep() method in java
The Thread class provides two methods for sleeping a thread:
public static void sleep(long miliseconds)throws
InterruptedException
public static void sleep(long miliseconds, int nanos)throws
InterruptedException
20
Example:
21
Every Java thread has a thread priority that helps the operating system
determine the order in which threads are scheduled
Priorities are represented by a number between MIN_PRIORITY( a
constant of 1) and MAX_PRIORITY (a constant of 10).
By default, every thread is given priority NORM_PRIORITY (a constant of
5)
In most cases, thread scheduler schedules the threads according to their
priority (known as preemptive scheduling). But it is not guaranteed
because it depends on JVM specification that which scheduling it chooses.
22
Each new thread inherits the priority of the thread that created
it
Priority methods
setPriority( int priorityNumber )
getPriority
yield - thread yields processor to threads of equal priority
Useful for non-timesliced systems, where threads run to
completion
23
24
Example:
25
start() is responsible for two things:
Instructing the JVM to create a new thread
Call your Thread object’s run method in the new thread
You might think of run as being similar to main
main is called by the JVM
Like main, the run method defines a starting point for the JVM
when the run method exits- The thread ‘ends’
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
26
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
An Executor object creates and manages a thread pool to execute Runnables
Executor advantages over creating threads yourself
Reuse existing threads to eliminate new thread overhead
Better performance It saves time because there is no need to create 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
27
Interface java.util.concurrent.ExecutorService
extends Executor
declares methods for managing the life cycle of an Executor
Can be instantiated by using static method newFixedThreadPool() of class
java.util.concurrent.Executors
methods
execute() returns immediately from each invocation
shutdown() notifies the ExecutorService to stop accepting new tasks, but continues
executing tasks that have already been submitted
……
ExecutorService es = Executors. newFixedThreadPooll();
es.execute(new Task());
es.execute(new Task());
28 ……
Synchronization in java is the capability to control the access
of multiple threads to any shared resource.
Java Synchronization is better option where we want to allow
only one thread to access the shared resource.
Other threads wait
A shared resource may be corrupted if it is accessed
simultaneously by multiple threads.
29
Mutual exclusion
Java provides built-in monitors to implement synchronization
Every object has a monitor and a monitor lock.
Monitor ensures that its object’s monitor lock is held by a maximum of
only one thread at any time
Can be used to enforce mutual exclusion
To enforce mutual exclusion
thread must acquire the lock before it can proceed with its operation
other threads attempting to perform an operation that requires the same
lock will be blocked until the first thread releases the lock
30
synchronized statement
Enforces mutual exclusion on a block of code
synchronized ( object ){
statements
} // end synchronized statement
where object is the object whose monitor lock will be
acquired (normally this)
A synchronized method is equivalent to a synchronized
statement that encloses the entire body of a method
31
32
There are two types of thread synchronization mutual exclusive
and inter-thread communication.
1) Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
2) Cooperation (Inter-thread communication in java)
33
Mutual Exclusive helps keep threads from interfering with one another while
sharing data. This can be done by two ways in java:
1) by synchronized method
2) by synchronized block
Concept of Lock in Java
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.
34
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
35
ii) Synchronized block
Synchronized block can be used to perform synchronization on any specific
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
same as the synchronized method.
Syntax to use synchronized block:
Example
36
Inter-thread communication or Co-operation is all about allowing
synchronized threads to communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread
is paused running in its critical section and another thread is allowed to enter
(or lock) in the same critical section to be executed.
o It is implemented by following methods of Object class:
1) wait()
2) notify()
3) notifyAll()
37
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
the synchronized method only otherwise it will throw exception.
38
2) notify() method
Wakes up a single thread that is waiting on this object's monitor.
If any threads are waiting on this object, one of them is chosen to
be awakened.
Syntax: public final void notify()
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax: public final void notifyAll()
Example
39
The process of inter-thread communication
40
The process of inter-thread communication
41
Deadlock in java is a part of multithreading. Deadlock can occur
in a situation when a thread is waiting for an object lock, that is
acquired by another thread and second thread is waiting for an
object lock that is acquired by first thread. Since, both threads
are waiting for each other to release the lock, the condition is
called deadlock.
Example
42
43