Professional Documents
Culture Documents
Chapter 2 - Multithreading
Chapter 2 - Multithreading
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.
In single-threaded applications lengthy activities must complete before others can begin
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
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.
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.
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
In another thread (e.g., the main), create an instance of the Thread subclass
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
19
The sleep() method of Thread class is used to sleep a thread for
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
5)
In most cases, thread scheduler schedules the threads according to their
22
Each new thread inherits the priority of the thread that created
it
Priority methods
getPriority
completion
23
24
Example:
25
start() is responsible for two things:
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
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.
Better performance It saves time because there is no need to create new thread.
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
java.util.concurrent.Executors
methods
shutdown() notifies the ExecutorService to stop accepting new tasks, but continues
……
es.execute(new Task());
es.execute(new Task());
28 ……
Synchronization in java is the capability to control the access
29
Mutual exclusion
lock will be blocked until the first thread releases the lock
30
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.
33
Mutual Exclusive helps keep threads from interfering with one another while
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
Example
36
Inter-thread communication or Co-operation is all about allowing
is paused running in its critical section and another thread is allowed to enter
(or lock) in the same critical section to be executed.
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
38
2) notify() method
Wakes up a single thread that is waiting on this object's monitor.
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
Example
42
43