MULTITHREADING IN JAVA
MULTITHREADING IN JAVA
PRESENTED BY
K.SHARMILA
ASSISTANT PROFESSOR
Process
⚫ An executing instance of a program is called process.
⚫ For example while writing java program in editor we can run MP3 player. At the same time we can
download file from net. All these task are executing simultaneously and independent of each other.
CPU
What is Thread?
⚫ A thread is a single sequential flow of execution within a program.
⚫ A thread is a subset of process.
⚫ Thread is considered as “Light Weight Process” because it use less resource than
process.
⚫ They share the address space of the process but process have their own address space.
⚫ JVM create the thread whose task is to define the main thread.
A program
A program
A Single Threaded
Program
class
ABC
{ ………. Beginning
...……..
………. Single-threaded
Body of Execution
...……..
……….
...…….. End
}
Application
Thread
When we execute an application:
1. The JVM creates a Thread object whose task is defined by the main()
method .
4. After executing all the statements, the method returns and the thread dies.
Process Thread
⚫Process can be divided into ⚫ Threads cannot be sub divided.
multiple threads
⚫ Threads of the same process share
⚫Each process has its own memory a common memory space.
space
⚫ It is difficult to create a ⚫ It is easy to create a
process thread
⚫ In word processor one thread take the input from keyboard and another thread check the spelling
mistakes and third thread count the words.
⚫ Railway ticket reservation system where multiple customers accessing the server.
⚫ Multiple account holders accessing their accounts simultaneously on the server. When you insert a
ATM card, it starts a thread for perform your operations.
Advantages of Multithreading
⚫ The main advantage is proper utilization or max utilization is possible.
⚫ Decreased cost of maintenance.
⚫ Time saving.
⚫ Improves the performance of complex applications.
⚫ Parallelize tasks.
Disadvantage of Multithreading
⚫ Complex debugging and testing processes.
⚫ Increased difficulty level in writing a program.
⚫ Unpredictable results.
Thread Life Cycle
❑ During the life time of a thread, there are many states it can
enter. They include:
1. Newborn state
2. Runnable State
3. Running State
4. Blocked State
5. Dead State
State diagram of a Thread
New Newborn
Thread
start
stop
Idle Thread
(Not Runnable) Blocked
1.Newborn State
❑ When we create a thread object, the thread is born and is said to be in newborn state.
The thread is not yet scheduled for running. At this state, we can do only one of the
following with it:
● Schedule it for running using start() method.
● Kill it using stop() method.
Newborn
start stop
Runnable
State Dead
State
2. Runnable state (start())
❑ The runnable state means that the thread is ready for execution and is waiting for the availability of
the processor.
❑ That is, the thread has joined the queue of threads that are waiting for execution.
❑ If all threads have equal priority, then they are given time slots for execution in round robin fashion. i.e.
first- come, first-serve manner.
3. Running
❑
State
Running means that the processor has given its time to the thread for its execution.
❑ The thread runs until it relinquishes control on its own or it is preempted by a higher priority thread.
4. Blocked State
❑ A thread is said to be blocked when it is prevented form entering into the runnable state and
subsequently the running state.
❑ This happens when the thread is sleeping, or waiting in order to satisfy certain requirements.
❑ A blocked thread is considered “ not runnable” but not dead and therefore fully qualified to run
again.
5. Dead State
❑ A running thread ends its life when is has completed executing its run() method. It is
a natural death.
❑ However, we can kill it by sending the stop message to it at any state thus causing
a premature death to it.
❑ A thread can be killed as soon it is born, or while it is running, or even when it is in
“not runnable” (blocked) condition.
Threads Methods
❖Thread Methods :
currentThread() sleep()
start() setpriority()
run() getpriority()
wait()
stop()
Join()
getName() isAlive()
setName()
currentThread() Method
This method return complete information about the current thread like it return name of current thread, name
of
group of current thread, priority number of current thread.
EXAMPLE
class Demo
{ Output
public static void main(String current thread information is
args[])
{ Thread[main,5,main]
System.out.println("current thread information is");
Current
System.out.println(Thread.currentThread()); Priority
thread no Group
thread
}
}
getName() Method
It is a sub method of current thread method and it return name of current thread.
EXAMPLE
class Demo output
{ name of current thread
public static void main(String args[]) main
{
System.out.println("name of current thread ");
System.out.println(Thread.currentThread().getName());
}
}
setName() Method
It is a child method of current thread method and it is use to set name of current thread.
EXAMPLE
class Demo
{ Output
public static void main(String args[]) name of current thread
{ Parent
Thread.currentThread().setName("Parent");
System.out.println("name of current thread ");
System.out.println(Thread.currentThread().getName());
}
}
getPriority() Method
It is a child method of current thread and this method return the priority number of the
current thread.
EXAMPLE
class Demo
{
public static void main(String args[])
{
System.out.println("current thread priority ");
System.out.println(Thread.currentThread().getPriority());
} Output
} current thread priority
5
setPriority() Method
It is a child method of current thread method and this method is used to set the priority number of
current thread.
EXAMPLE
class Demo
{ Output
public static void main(String args[]) current thread priority
{ 9
Thread.currentThread().setPriority(9);
System.out.println("current thread priority ");
System.out.println(Thread.currentThread().getPriority());
}
}
Sleep() Method
This method is used to block the current thread until the given sleep time is not
complete.
sleep(t)
Runnable Sleeping
Running
EXAMPLE
class Demo try
{ {
public static void main(String Thread.sleep(2000); //2
sec//
args[])
}
{
catch(Exception e)
int i;
{ Output
for(i=1;i<=5;i++)
} 1
{ } 2
System.out.println(i); }
3
}
4
5
Thread Declaration
Thread can be declared in two ways :
⚫ Another difference between Thread and Runnable comes from the fact that you are extending Thread class
just for run() method but you will get overhead of all other methods which come from Thread class. So, if
your goal is to just write some code in run() method for parallel execution then use Runnable instead of
extending Thread class.
⚫ When you extends Thread class, each of your thread creates unique object and associate with it.
⚫ When you implements Runnable, it shares the same object to multiple threads.
⚫ When you implements Runnable, you can save a space for your class to extend any other class in future
or now.
stop() Method
This method stops a thread
completely.
class Thread2 extends Thread class Demo
EXAMPLE
class Thread1 extends
{ {
Thread
{ public void run() public static void main(String args[])
public void run() { {
{ for(int j=0;j<5;j++) Thread1 t1=new Thread1();
for(int i=0;i<5;i++) Thread2 t2=new Thread2();
{
{ if(j==3) t1.start();
if(i==2) stop(); t2.start(); output
stop(); } Thread 1:0
System.out.println("Thread 2:"+j);
System.out.println("Thread1:"+i); } Thread 1:1
} }
Thread 2:0
} }
Thread 2:1
} }
Thread 2:2
yield() Method
yield() method causes to pause current executing thread for giving the chance to remaining waiting threads of
same
priority.
execution
If there are noonce again.
waiting threads or all waiting threads have low priority then the same thread will continue its
Thread.yield
()
Ready/ Runnable
Running
EXAMPLE
class Thread1 extends Thread class Thread2 extends Thread class Demo
{ { {
public void run() public void run() public static void main(String args[])
{ {
{
for(int i=0;i<5;i++) Thread1 t1=new Thread1();
for(int j=0;j<5;j++)
{ Thread2 t2=new Thread2();
{
if(i==2) t1.start();
System.out.println("Thread2:“
yield(); t2.start();
System.out.println("Thread 1:"+i); +j);
}
} }
}
System.out.println("Exit from thread1"); System.out.println("Exit
} from thread2");
} }
}
Output
Thread 1:0
Thread 1:1
Thread 2:0
Thread 2:1
Thread 2:2
Thread 2:3
Thread 2:4
Exit from thread2
Thread 1:2
Thread 1:3
Thread 1:4
Exit from thread1
isAlive() Method
isAlive() method tests if the thread is alive or not and it return boolean value.
class Demo
class MyThread extends Thread {
{ public static void main(String args[])
public void run() {
{ MyThread t1=new MyThread(); output
for(int i=0;i<5;i++) t1.start(); new status :true
{ System.out.println("new status status :true
System.out.println("status :"+isAlive()); :"+t1.isAlive()); status :true
} } status :true
} } status :true
}
status :true
join() Method
⚫ If a thread wants to wait until completing some other thread then we should go for
join method.
⚫ For example if a thread t1 wants to wait until completing t2 then “t1 has to call t2.join()”.
⚫ If t1 executes t2.join() then immediately t1 will enter into waiting state until t2 completes.
⚫ Once t2 completes then t1 will continue its execution.
EXAMPLE WITHOUT USING JOIN
class MyThread extendsThread class Demo
{
{
public void run()
public static void main(String args[])
{
{
for(int i=0;i<5;i++)
MyThread t1=new MyThread();
{
t1.start();
System.out.println("MyThread :"+i);
for(int j=0;j<5;j++)
}
{
System.out.println("Exit from my thread");
System.out.println("Main Thread :"+j);
}
}
}
System.out.println("Exit from main thread");
}
}
Output
Main Thread :0
MyThread :0
Main Thread :1
Main Thread :2
MyThread :1
Main Thread :3
MyThread :2
Main Thread :4
MyThread :3
Exit from main thread
MyThread :4
Exit from my thread
EXAMPLE USING JOIN METHOD
class MyThread extends Thread MyThread t1=new MyThread();
{ t1.start();
public void run() for(int j=0;j<5;j++)
{ {
for(int i=0;i<5;i++) try
{ {
System.out.println("MyThread :"+i); t1.join();
} }
System.out.println("Exit from my thread"); catch(Exception e)
} {
} }
class Demo }
{ System.out.println("Exit from
public static void main(String args[]) main thread");
{ }
output
MyThread :0
MyThread :1
MyThread :2
MyThread :3
MyThread :4
Exit from my thread
Main Thread :0
Main Thread :1
Main Thread :2
Main Thread :3
Main Thread :4
Exit from main thread
Synchronization
Synchronization in java is the capability of 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.
Why we use :
1. To prevent thread interference.
2. To prevent consistency problem.
Synchronized method is used to lock an object for any shared resource.
Example without using Synchronized
class B extends Thread class Demo
{ {
public void run() public static void main(String args[])
{ {
for(int i=0;i<5;i++) B b=new B();
Thread t1=new Thread(b);
{
t1.setName("t1:");
System.out.println(Thread.currentThread().getName()+(i));
t1.start();
}
Thread t2=new Thread(b);
}
t2.setName("t2:");
}
t2.start();
}
}
output
t1:0
t1:1
t2:0
t1:2
t2:1
t1:3
t2:2
t1:4
t2:3
t2:4
Example using Synchronized
class Demo
{
class B extends Thread public static void main(String args[])
{
{
public void run()
B b=new B();
{
Thread t1=new Thread(b);
synchronized(this)
t1.setName("t1:");
{
for(int i=0;i<5;i++) t1.start();
{ Thread t2=new Thread(b);
System.out.println(Thread.current t2.setName("t2:");
Thread().getName()+(i)); t2.start();
} }
}
}
}
}
output
t1:0
t1:1
t1:2
t1:3
t1:4
t2:0
t2:1
t2:2
t2:3
t2:4
wait() Method
⚫ Two thread communicate each other using wait, notify and notifyAll methods.
⚫ Wait, notify and notifyAll method are present in object class but not in thread class.
⚫ Wait, notify and notifyAll method are called from synchronized area otherwise we get
run time exception error saying “illegal moniter state exception”
⚫ If a thread called wait method immediately enter in waiting state but in case of
notify method it does not immediately enter in waiting state.
⚫Wait, notify and notifyAll methods are only method which release the lock.
Note:
Every wait method throws interrupted exception which is checked exception hence whenever
we are using wait method compulsory we should handle these interrupted exception either
by try, catch or by throws keyword otherwise we will get compile time error
if waiting state get notify function,
Another time complete ,if waiting thread get interrupted
Waiting Waitin
state to g
get lock State
If waiting thread
got lock
Ready/
Running
Runnabl
e
EXAMPLE
class ThreadA
{
public static void main(String args[]) throws Exception
{
ThreadB b=new ThreadB();
b.start();
synchronized(b)
{
System.out.println("main thread trying to call wait
method"); b.wait();
System.out.println("main thread got notification");
System.out.println(b.total);
}
}
}
class ThreadB extends Thread output
{ main thread trying to call wait
int total=0;
method child thread starts calculation
public void run()
child thread try to give notification
{
main thread got notification
synchronized(this)
{ 5050
System.out.println("child thread starts calculation");
for(int i=1;i<=100;i++)
{
total=total+i;
}
System.out.println("child thread try to give notification");
this.notify();
}
}
}
Producer consumer problem
⚫ Producer thread is responsible to produce items to the queue and consumer thread is responsible
is responsible to consume items to the queue.
⚫ If queue is empty then consumer thread will call wait method and enter into waiting state.
⚫ After producing items to the queue producer thread is responsible to call notify method then
waiting consumer will get notification and continue its execution with updated items.
class ConsumerThread class ProducerThread
{
{
consume()
{ Produce()
synchronized(q) {
{ synchronized(q)
if(q is empty) {
produce items to the queue
else
consume items
} }
} }
} }
Difference between notify() and
notifyAll()
⚫ We can use notify method to give notification for only one waiting thread if multiple
threads are waiting then only one thread will be notify and remaining thread will have to
wait for further notification.
⚫ We can use notifyAll to give the notification for all waiting threads of a particular object
even though multiple thread notify but execution will be perform one by one because
threads are require lock and only one lock is available.
Thank You