Module_3_Threads
Module_3_Threads
2
Threads States or Life Cycle Of Thread
• A thread in Java at any point of time exists in any one of the following states. A thread lies only in one
of the states at any instant:
1. New State
2. Active State
3. Blocked State
4. Waiting State
5. Timed Waiting State
6. Terminated State
3
Threads states
• There are multiple states of the thread in a lifecycle as mentioned below:
• New Thread: When a new thread is created, it is in the new state. The thread has not yet started to run
when the thread is in this state. When a thread lies in the new state, its code is yet to be run and hasn’t
started to execute.
• Active State: A Thread that is a new state by default gets transferred to Active state when it invokes
the start() method, his Active state contains two sub-states namely:
• Runnable State: A thread in the runnable state is prepared to execute the code. When a new thread's
start() method is called, it enters a runnable state. In the runnable environment, the thread is ready for
execution and is awaiting the processor's availability (CPU time). That is, the thread has entered the
queue (line) of threads waiting for execution.
• Running State: When the Thread Receives CPU allocated by Thread Scheduler, it transfers from the
“Runnable” state to the “Running” state, and after the expiry of its given time slice session, it again
moves back to the “Runnable” state and waits for its next time slice.
• Blocked: The thread will be in blocked state when it is trying to acquire a lock (CPU) but currently the
lock (CPU) is acquired by the other thread. The thread will move from the blocked state to runnable
state when it acquires the lock.
4
Threads States
• Waiting state: The thread will be in waiting state when it calls wait() method or join() method. It will
move to the runnable state when other thread will notify or that thread will be terminated.
• Timed Waiting: A thread lies in a timed waiting state when it calls a method with a time-out
parameter. A thread lies in this state until the timeout is completed or until a notification is received.
For example, when a thread calls sleep or a conditional wait, it is moved to a timed waiting state.
• Terminated State: A thread terminates because of either of the following reasons:
• Because it exits normally. This happens when the code of the thread has been entirely executed by
the program.
• Because there occurred some unusual erroneous event, like a segmentation fault or an unhandled
exception.
5
How to create a thread in Java
• There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
6
Threads
• Example:
7
Commonly used methods of Thread class:
• public void run(): is used to perform action for a thread.
• public void start(): starts the execution of the thread. JVM calls the run() method on the thread.
• public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.
• public void join(): waits for a thread to die.
• public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
• public int getPriority(): returns the priority of the thread.
• public int setPriority(int priority): changes the priority of the thread.
• public String getName(): returns the name of the thread.
• public void setName(String name): changes the name of the thread.
• public Thread currentThread(): returns the reference of currently executing thread.
• public int getId(): returns the id of the thread.
8
• public Thread.State getState(): returns the state of the thread.
• public boolean isAlive(): tests if the thread is alive.
• public void yield(): causes the currently executing thread object to temporarily pause and allow other
threads to execute.
• public void suspend(): is used to suspend the thread(depricated).
• public void resume(): is used to resume the suspended thread(depricated).
• public void stop(): is used to stop the thread(depricated).
• public boolean isDaemon(): tests if the thread is a daemon thread.
• public void setDaemon(boolean b): marks the thread as daemon or user thread.
• public void interrupt(): interrupts the thread.
• public boolean isInterrupted(): tests if the thread has been interrupted.
• public static boolean interrupted(): tests if the current thread has been interrupted.
9
2. By implementing Runnable interface:
11
4) Using the Thread Class: Thread(Runnable r, String name):
20
Mutual Exclusive:
• Mutual Exclusive helps keep threads from interfering with one another while sharing data.
• There are three types of Mutual Exclusive mentioned below:
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
21
Understanding the problem without Synchronization
class Table{ class Main{
//method not synchronized public static void main(String
void printTable(int n){ args[]){
for(int i=1;i<=5;i++){ Table obj = new Table();//only one
System.out.println(n*i); object
try{
Thread.sleep(400); MyThread1 t1=new MyThread1(obj);
}catch(Exception e){System.out.println(e);} MyThread2 t2=new MyThread2(obj);
}}} t1.start();
class MyThread1 extends Thread{ t2.start();
Table t; }}
MyThread1(Table t){ Output:
this.t=t;
} 5
public void run(){ 100
t.printTable(5); 10
}} 200
class MyThread2 extends Thread{ 15
Table t; 300
MyThread2(Table t){
20
this.t=t;
} 400
public void run(){ 500
t.printTable(100); 25 22
}}
Java 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.
23
problem solving using Synchronized Method
class Main{
class Table{ public static void main(String
//method is synchronized args[]){
synchronized void printTable(int n){
for(int i=1;i<=5;i++){ Table obj = new Table();//only one
System.out.println(n*i); object
try{ MyThread1 t1=new MyThread1(obj);
Thread.sleep(400); MyThread2 t2=new MyThread2(obj);
}catch(Exception e){System.out.println(e);} t1.start();
}}} t2.start();
class MyThread1 extends Thread{
}}
Table t;
MyThread1(Table t){ Output:
this.t=t; 5
} 10
public void run(){ 15
t.printTable(5); 20
}}
25
class MyThread2 extends Thread{
Table t; 100
MyThread2(Table t){ 200
this.t=t; 300
} 400
public void run(){ 500 24
t.printTable(100);
Synchronized Block in Java
• Synchronized block can be used to perform synchronization on any specific resource of the method.
• Suppose we have 50 lines of code in our method, but we want to synchronize only 5 lines, in such
cases, we can use synchronized block.
• If we put all the codes of the method in the synchronized block, it will work same as the synchronized
method.
Points to Remember:
• Synchronized block is used to lock an object for any shared resource.
• Scope of synchronized block is smaller than the method.
• A Java synchronized block doesn't allow more than one JVM, to provide access control to a shared
resource.
• The system performance may degrade because of the slower working of synchronized keyword.
• Java synchronized block is more efficient than Java synchronized method.
Syntax:
synchronized (objectidentifier) {
//code block
} 25
problem solving using Synchronized Block
class Table{ class Main{
void printTable(int n){
public static void main(String args[])
for(int i=1;i<=5;i++){
System.out.println(n*i);
{
try{ Table obj = new Table();//only one
Thread.sleep(400); object
}catch(Exception e){System.out.println(e);} MyThread1 t1=new MyThread1(obj);
}}}
MyThread2 t2=new MyThread2(obj);
class MyThread1 extends Thread{
Table t; t1.start();
MyThread1(Table t){ t2.start();
this.t=t; }}
} Output:
public void run(){ 5
synchronized(t) {
10
t.printTable(5);
}}} 15
class MyThread2 extends Thread{ 20
Table t; 25
MyThread2(Table t){ 100
this.t=t;
}
200
public void run(){ 300
synchronized(t) { 400
t.printTable(100); 500 26
}}}
Static Synchronization
• If you make any static method as synchronized, the lock will be on the class not on object.
27
problem solving using Static Synchronized
class Table{ class Main{
synchronized static void printTable(int n){ public static void main(String args[]){
for(int i=1;i<=5;i++){ //Table obj = new Table();//only one
System.out.println(n*i); object
try{ MyThread1 t1=new MyThread1();
Thread.sleep(400); MyThread2 t2=new MyThread2();
}catch(Exception e){System.out.println(e);} t1.start();
}}} t2.start();
class MyThread1 extends Thread{ }}
Output:
public void run(){ 5
Table.printTable(5); 10
}} 15
class MyThread2 extends Thread{ 20
public void run(){ 25
Table.printTable(100); 100
200
}}
300
400
500 28
Inter Thread Communication
• 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.
• It is implemented by following methods of Object class:
1. wait()
2. notify()
3. notifyAll()
29
1) wait() method:
• The 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.
Method Description
public final void wait()throws
It waits until object is notified.
InterruptedException
public final void wait(long
It waits for the specified amount of
timeout)throws
time.
InterruptedException
2) notify() method
• The 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()
30
3) notifyAll() method:
• Wakes up all threads that are waiting on this object's monitor.
Syntax:
public final void notifyAll()
31
Example
class Chat { class T1 implements Runnable {
boolean flag = false; Chat m;
public synchronized void Question(String msg) {
String[] s1 = { "Hi", "How are you ?",
if (flag) {
try { "I am also doing fine!" };
wait(); public T1(Chat m1) {
} catch (InterruptedException e) { this.m = m1;
e.printStackTrace(); }
}} public void run() {
System.out.println(msg); for (int i = 0; i < s1.length; i++) {
flag = true; m.Question(s1[i]);
notify(); }}}
}
class T2 implements Runnable {
public synchronized void Answer(String msg) {
if (!flag) { Chat m;
try { String[] s2 = { "Hi", "I am good, what about
wait(); you?",
} catch (InterruptedException e) { "Great!" };
e.printStackTrace(); public T2(Chat m2) {
}} this.m = m2;
System.out.println(msg); }
flag = false; public void run() {
notify();
for (int i = 0; i < s2.length; i++) {
}}
m.Answer(s2[i]);
}}} 32
public class MyThread {
public static void main(String[] args) {
Chat m = new Chat();
Runnable obj1= new T1(m);
Runnable obj2= new T2(m);
Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);
t1.start();
t2.start(); Output:
} Hi
} Hi
How are you ?
I am good, what about you?
I am also doing fine!
Great!
33
d
• If
34
d
• If
35