Multithreading in Java
Multithreading in Java
Anupama Mishra
Multithreading
Tasks:
There are two types of Executing the tasks:
2. Multi tasking: Executing more than one task at a time is called multi
tasking.
Anupama Mishra
Thread:
•Thread is a smallest unit of code.
Advantage of Multithreading:
Anupama Mishra
Multithreading
Life cycle of a thread:
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
Anupama Mishra
Multithreading
Thread Life Cycle
Anupama Mishra
Multithreading
1.New (Newborn State):
When we create a thread object using Thread class, thread is born and is
known to be in Newborn state. That is, when a thread is born, it enters into
new state but the start() method has not been called yet on the instance.
2.Runnable state:
•Runnable state means a thread is ready for execution. When the start()
method is called on a new thread, thread enters into a runnable state.
•In runnable state, thread is ready for execution and is waiting for
availability of the processor (CPU time). That is, thread has joined queue
(line) of threads that are waiting for execution.
Anupama Mishra
Multithreading
Anupama Mishra
Multithreading
3.Running state:
•Running means Processor (CPU) has allocated time slot to thread for
its execution. When thread scheduler selects a thread from the runnable
state for execution.
•In running state, processor gives its time to the thread for execution and
executes its run() method.
•A thread can come into running state only from runnable state.
Anupama Mishra
Multithreading
Running state:
A running thread may give up the following situations and can enter
into the Blocked state:
1. When sleep() method is invoked on a thread to sleep for specified time
period.
3. When wait() method is called on a thread to wait for some time. The
thread in wait state can be run again using notify() or notifyAll()
method.
Anupama Mishra
Multithreading
4.Blocked state:
5.Dead state:
A thread dies or moves into dead state automatically when its run()
method completes the execution of statements. That is, a thread is
terminated or dead when a thread comes out of run() method. A thread
can also be dead when the stop() method is called.
Anupama Mishra
Multithreading
Creation of a thread
1. By Extending Thread class:
The first way to create a thread is to create a new class that extends the
Thread class and then to create an instance of this class. The class must
override the run() method which is the entry point for the new thread.
Anupama Mishra
Multithreading
1.By Extending the Thread class
• Threads are implemented as objects that contains a method called run()
class MyThread extends Thread
{
public void run()
{
// thread body of execution
}
}
• Create a thread:
MyThread thr1 = new MyThread();
Anupama Mishra
Multithreading
Three threads example
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("\t From ThreadA: i= "+i);
}
System.out.println("Exit from A");
}
}
class B extends Thread
{
public void run()
{
for(int j=1;j<=5;j++)
{
System.out.println("\t From ThreadB: j= "+j);
}
System.out.println("Exit from B");
}
} Anupama Mishra
Three threads example:
class C extends Thread
{
public void run()
{
for(int k=1;k<=5;k++)
{
System.out.println("\t From ThreadC: k= "+k);
}
System.out.println("Exit from C");
}
}
class ThreadTest
{
public static void main(String args[])
{
new A().start();
new B().start();
new C().start();
}
}
Anupama Mishra
Three threads example: Run 1
Anupama Mishra
Three threads example: Run 2
Anupama Mishra
Multithreading
Thread class methods
• start() Starts execution of the thread.
• stop() Terminates the current thread.
• suspend() Suspends the thread.
• resume() Restarts the suspended thread.
• sleep() This method suspends execution of the executing thread for the
specified number of milliseconds. It can throw an interrupted Exception.
• Thread priorities are integers that specify the relative priority of one
thread to another.
• Higher priority thread doesn't run any faster than a lower priority thread.
• Instead a thread‟s priority is used to decide when to switch from one
running thread to the next. This is called as context switch.
Anupama Mishra
Multithreading
Thread priorities
• ThreadName.setPriority(intNumber)
– MIN_PRIORITY = 1
– NORM_PRIORITY=5
– MAX_PRIORITY=10
Anupama Mishra
Thread priorities Example:
public class A implements Runnable
{
public void run() {
System.out.println(Thread.currentThread());
}
public static void main(String[] args) {
A a = new A();
Thread t = new Thread(a, "NewThread");
System.out.println("Priority of Thread: " +t.getPriority());
System.out.println("Name of Thread: " +t.getName());
t.start();
}
} Anupama Mishra
Multithreading
Thread priorities
class A extends Thread
{
public void run()
{
System.out.println("Thread A started");
for(int i=1;i<=4;i++)
{
System.out.println("\t From ThreadA: i= "+i);
}
System.out.println("Exit from A");
}
}
class B extends Thread
{
public void run()
{
System.out.println("Thread B started");
for(int j=1;j<=4;j++)
{
System.out.println("\t From ThreadB: j= "+j);
}
System.out.println("Exit from B");
}
Anupama Mishra
}
Thread priorities
class C extends Thread
{
public void run()
{
System.out.println("Thread C started");
for(int k=1;k<=4;k++)
{
System.out.println("\t From ThreadC: k= "+k);
}
System.out.println("Exit from C"); } }
class ThreadPriority
{
public static void main(String args[])
{
A threadA=new A();
B threadB=new B();
C threadC=new C();
threadC.setPriority(Thread.MAX_PRIORITY);
threadB.setPriority(threadA.getPriority()+1);
threadA.setPriority(Thread.MIN_PRIORITY);
System.out.println("Started Thread A");
threadA.start();
System.out.println("Started Thread B");
threadB.start();
System.out.println("Started Thread C");
threadC.start();
System.out.println("End of main thread");
}
} Anupama Mishra
Multithreading
Thread synchronization
•For Example: One thread may try to read a record from a file while
another is still writing to the same file.
Anupama Mishra
Thread synchronization
2. At a time only one thread can access the Monitor. A second thread
cannot enter the monitor until the first comes out. Till such time the other
thread is said to be waiting.
Anupama Mishra
Thread synchronization
Anupama Mishra
Thread synchronization
Anupama Mishra
Thread synchronization
Synchronized methods
• If one thread tries to read the data and other thread tries to update
the same data, it leads to inconsistent state.
• This can be prevented by synchronising access to the data.
• Use “Synchronized” methods:
Anupama Mishra