Introduction Multitasking:
Executing several tasks simultaneously is the concept of multitasking.
There are two types of multitasking’s.
1. Process based multitasking.
2. Thread based multitasking
Process based multitasking:
Executing several tasks simultaneously where each task is a separate independent
process such type of multitasking is called process-based multitasking.
[Link] typing a java program in the editor we can able to listen mp3 audio songs at the
same time we can download a file from the net all these tasks are independent of each
other and executing simultaneously and hence it is Process based multitasking.
[Link] type of multitasking is best suitable at "os level"
Thread based multitasking:
Executing several tasks simultaneously where each task is a separate independent
part of the same program, is called Thread based multitasking.
And each independent part is called a "Thread".
1. This type of multitasking is best suitable for "programmatic level".
java provides in built support for multithreading through a rich API (Thread, Runnable,
ThreadGroup, ThreadLocal...etc).
The main important application areas of multithreading are:
To implement multimedia graphics.
To develop animations.
To develop video games etc.
To develop web and application servers
Whether it is process based or Thread based the main objective of
multitasking is to improve performance of the system by reducing response
time.
Thread:-
1) The independent execution technical name is called thread.
2) The thread is light weight process because whenever we are creating thread it is
not occupying the separate memory it uses the same memory.
3) Executing more than one thread a time is called multithreading.
Single threaded model:-
class Test
public static void main(String[] args)
[Link]("Hello World!");
[Link]("hi Sai");
[Link]("hello TwinkleTech");
class Test
public static void main(String[] args)
[Link]("Hello World!");
Thread t=[Link]();
[Link]("currrent thread information is : "+t);//[main,5,main]
[Link]("currrent thread priority is : "+[Link]());//5
[Link]("currrent thread name is : "+[Link]());
[Link]("hi sai");
[Link]("hello twinkleTech");
}
There are two different ways to create a thread is available
1) By using Thread Class
2) By using Runnable interface
class MyThread extends Thread
public void run()
[Link](“hi");
[Link](“welcome");
};
class ThreadDemo
public static void main(String[] args)
MyThread t=new MyThread();
[Link]();
}
}
Note :-
1) Whenever we are calling [Link]() method the JVM search for the start() in the MyThread
class but the start() method is not present in the MyThread class so JVM goes to parent class
called Thread class and search for the start() method.
2) In the Thread class start() method is available hence JVM is executing start() method.
3) Whenever the thread class start() that start() is responsible person to call run() method.
4) Finally the run() automatically executed whenever we are calling start() method.
5) Whenever we are giving a chance to the Thread class start() method then only a new
thread will be created.
Life cycle stages are:-
1) New
2) Ready
3) Running state
4) Blocked / waiting / non-running mode
5) Dead state
New :- MyThread t=new MyThread();
Ready :- [Link]()
Running state:- If thread scheduler allocates CPU for particular thread. Thread goes to
running state The Thread is running state means the run() is executed.
Blocked State:- If the running thread got interrupted of goes to sleeping state at that
moment it goes to the blocked state.
Dead State:- If the business logic of the project is completed means run() over thread goes
dead state.
implementing Runnable interface
class MyClass implements Runnable
public void run()
[Link](“Sai");
[Link]("body of the thread");
class ThreadDemo
public static void main(String[] args)
MyClasss obj=new MyClass();
Thread t=new Thread(obj);
[Link]();
}
2nd way
class Test
public static void main(String[] args)
Runnable r1=new Runnable(){ public void run()
for(int i=0;i<10;i++)
[Link]("welcome:
"+[Link]().getName());
};
Thread t1=new Thread(r1);
[Link]("t1");
[Link]();
for(int i=0;i<10;i++)
[Link]("hi: "+[Link]().getName());
}
multiple threads are performing multiple operation.
class MyThread1 extends Thread
public void run()
[Link]("mythread1 task");
class MyThread2 extends Thread
public void run()
[Link]("mythread2 task");
class MyThread3 extends Thread {
public void run()
[Link]("Mythread3 task");
class ThreadDemo {
public static void main(String[] args) {
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
MyThread3 t3=new MyThread3();
[Link]();
[Link]();
[Link]();
}}
Getting and setting names of Thread:-
Every Thread in java has some name if may be default name provided by the jvm or
customized name provided by the programmer.
Public final String getName()
Public final void setName(String name)
class MyThread extends Thread
class Test {
public static void main(String args[]) {
[Link]([Link]().getName());
MyThread t=new MyThread();
[Link]([Link]());
[Link]().setName("meena");
[Link]([Link]().getName());
Thread Priorities:-
1. Every Thread in java has some priority. It may be default priority provided by the JVM or
customized priority provided by the programmer.
2. The valid range of thread priorities is 1 – 10. Where one is lowest priority and 10 is highest
priority.
3. The default priority of main thread is 5. The priority of child thread is inherited from the
parent.
4. If two threads having the same priority then we can’t expect exact execution order it
depends upon Thread Scheduler.
5. The thread which is having low priority has to wait until completion of high priority
threads.
6. Three constant values for the thread priority.
a. MIN_PRIORITY = 1
b. NORM_PRIORITY = 5
c. MAX_PRIORITY = 10
Thread class defines to get and set priority of a Thread.
Public final int getPriority()
Public final void setPriority(int priority)
Here ‘priority’ indicates a number which is in the allowed range of 1 – 10. Otherwise we will
get Runtime exception saying “IllegalArgumentException”.
class SaiThread extends Thread {
public void run() {
[Link]("Enter into thread Sai");
[Link]("thread Sai is started");
for (int i=0;i<10 ;i++ )
[Link](“welcome");
[Link]("thread Sai is ended");
};
class PrasannaThread extends Thread
public void run()
[Link]("Enter into thread Prasanna");
[Link]("thread Prasanna is started");
for (int i=0;i<10 ;i++ )
{
[Link](“Prasanna");
[Link]("thread Prasanna is ended");
};
class TwinkleThread extends Thread
public void run()
[Link]("Enter into thread Twinkle");
[Link]("thread Twinkle is started");
for (int i=0;i<10 ;i++ )
[Link](“Twinkle");
[Link]("thread Twinkle is ended");
};
class ThreadDemo {
public static void main(String[] durga) {
SaiThread thread1=new SaiThread();
PrasannaThread thread2=new PrasannaThread();
TwinkleThread thread3=new TwinkleThread();
[Link](Thread.MAX_PRIORITY);
[Link]([Link]());
[Link](Thread.MIN_PRIORITY);
[Link]([Link]());
[Link]([Link]()+1);
[Link]([Link]());
[Link]("starting of Sai Thread");
[Link]();
[Link]("starting of Prasanna Thread");
[Link]();
[Link]("starting of Twinkle Thread");
[Link]();
} };
Some of the thread class methods:-
Sleep():-
The sleep() method causes the current thread to sleep for a specified amount of time in
milliseconds.
public static void sleep(long millis) throws InterruptedException
public static void sleep(long millis,int nanosec) throws InterruptedException
class Test {
public static void main(String[] args) {
try {
for (int i=0;i<10 ;i++)
[Link](“sai");
[Link](5*1000);//5 seconds
[Link](5*60*1000);// 5 minits
}
catch (InterruptedException ie)
[Link]("the thread is got innterupted");
[Link]():-
Yield() method causes to pause current executing Thread for giving the chance for
waiting threads of same priority.
If there are no waiting threads or all threads are having low priority then the same
thread will continue its execution once again.
Public static native void yield();
class MyThread extends Thread {
public void run()
for(int i=0;i<10;i++)
[Link]();
[Link]("child thread");
class ThreadYieldDemo {
public static void main(String[] args) {
MyThread t1=new MyThread();
[Link]();
for(int i=0;i<10;i++)
{
[Link]("main thread");
[Link]():-
If a Thread wants to wait until completing some other thread, then we should go for join()
method.
Public final void join()throws InterruptedExcetion
Public final void join(long ms)throws InterruptedException
Public final void join(long ms, int ns)throws InterruptedException
class MyThread extends Thread {
public void run() {
for (int i=0;i<5;i++ ) {
try{
[Link](“sai");
[Link](3*1000); }
catch(InterruptedException iee) {
[Link]("gettting innterupted exctpion");
}}
class ThreadDemo {
public static void main(String[] args) {
MyThread t1=new MyThread();
MyThread t2=new MyThread();
[Link]();
try {
[Link]();
catch (InterruptedException ie)
[Link]("interrupted Exception");
[Link](); } };
isAlive():- used to check whether the thread is live or not.
Public Boolean isAlive()
[Link]():-
This method is used to find out the number of methods in active state.
Public static int activeCount();
[Link]():-
This method is used to represent current thread class object.
Public static thread currentThread()
[Link]():-
getId() is used to generate id value for each and every thread.
Public long getId()
Interrupted():-
A thread can interrupt another sleeping or waiting thread.
For this Thread class defines interrupt() method.
Public void interrupt()
Effect of interrupt() method call:-
class MyThread extends Thread {
public void run() {
try {
for (int i=0;i<10;i++ ) {
[Link]("i am sleeping ");
[Link](5000);
catch (InterruptedException ie) {
[Link]("i got interupted by interrupt() call");
} };
class ThreadDemo
public static void main(String[] args)
MyThread t=new MyThread();
[Link]();
[Link]();
};
class MyThread extends Thread
public void run()
for (int i=0;i<10;i++)
[Link](2000);
[Link](“Vasavi College");
}
}
};
class ThreadDemo
public static void main(String[] args)throws Exception
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
MyThread3 t3=new MyThread3();
[Link]();
[Link]();
[Link]();//4-threads
[Link]();
[Link]([Link]());//thread-0
[Link]([Link]());
[Link]([Link]());
[Link]("sneha");
[Link]([Link]());//sneha
[Link]([Link]().getName());//main
[Link]().setName("poornima");
[Link]([Link]().getName());//poornima
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]().getPriority());
[Link]([Link]());
[Link]().setPriority(10);
[Link]([Link]().getPriority());
for (int i=0;i<5;i++)
[Link](5000);
[Link]();
[Link]("main thread");
};
Synchronized :-
Synchronized modifier is applicable for methods but not for classes and variables.
If a method or a block declared as synchronized then at a time only one Thread is
allowed to operate on the given object.
The main advantage of synchronized modifier is we can resolve data inconsistency
problems.
But the main disadvantage of synchronized modifier is it increases the waiting time
of the Thread and effects performance of the system .Hence if there is no specific
requirement it is never recommended to use.
class Display
synchronized void msg(String name)
{
for(int i=0;i<5;i++)
[Link]("Good Morning:
"+[Link]().getName());
try
[Link](1000);
catch(InterruptedException e)
class Student extends Thread
Display d;
String name;
Student(Display d,String name)
this.d=d;
[Link]=name;
public void run()
[Link](name);
}
class Test
public static void main(String[] args)
Display d1=new Display();
Student s1=new Student(d1,"suresh");
Student s2=new Student(d1,"hari");
Student s3=new Student(d1,"babu");
[Link]("suresh");
[Link]("hari");
[Link]("babu");
[Link](Thread.MAX_PRIORITY);
[Link](Thread.MIN_PRIORITY);
[Link](Thread.NORM_PRIORITY);
[Link]();
[Link]();
[Link]();
Daemon threads:-
The threads wchich are executed at background is called daemon threads.
Ex:- garbage collector,ThreadSchedular, default exceptional handler.
Non-daemon threads:-
The threads which are executed fore ground is called non-daemon threads.
Ex:- normal java application.
Dead lock:
If 2 Threads are waiting for each other forever(without end) such type of
situation(infinite waiting) is called dead lock.
There are no resolution techniques for dead lock but several
prevention(avoidance) techniques are possible.
Synchronized keyword is the cause for deadlock hence whenever we are using
synchronized keyword we have to take special care.
class A
synchronized void m1(B b)
[Link]("A class executing....m1()");
try
[Link](1000);
catch(InterruptedException e)
[Link]("A trying calling [Link]()");
[Link]();
synchronized void show()
{
[Link]("InSide A, This is show method");
class B
synchronized void m2(A a)
[Link]("B class executing.... m2()");
try
[Link](1000);
catch(InterruptedException e)
[Link]("B trying calling [Link]()");
[Link]();
synchronized void show()
[Link]("InSide B, This is show method");
}
class Test implements Runnable
A a=new A();
B b=new B();
Test()
Thread t=new Thread(this);
[Link]();
a.m1(b);
public void run()
b.m2(a);
public static void main(String[] args)
new Test();
Deadlock vs Starvation:
A long waiting of a Thread which never ends is called deadlock.
A long waiting of a Thread which ends at certain point is called starvation.
A low priority Thread has to wait until completing all high priority Threads.
This long waiting of Thread which ends at certain point is called starvation.
RACE condition:
Executing multiple Threads simultaneously and causing data inconsistency problems is
nothing but Race condition
we can resolve race condition by using synchronized keyword.
suspend and resume methods:
A Thread can suspend another Thread by using suspend() method then that
Thread will be paused temporarily.
A Thread can resume a suspended Thread by using resume() method then
suspended Thread will continue its execution.
1. public final void suspend();
2. public final void resume();
Both methods are deprecated and not recommended to use.
Inter Thread communication (wait(),notify(), notifyAll()):
Two Threads can communicate with each other by using wait(), notify() and
notifyAll() methods.
The Thread which is required updation it has to call wait() method on the
required object then immediately the Thread will entered into waiting state.
The Thread which is performing updation of object, it is responsible to give
notification by calling notify() method.
After getting notification the waiting Thread will get those updations.
wait(), notify() and notifyAll() methods are available in Object class but not in
Thread class because Thread can call these methods on any common object.
To call wait(), notify() and notifyAll() methods compulsory the current Thread
should be owner of that object
i.e., current Thread should has lock of that object
i.e., current Thread should be in synchronized area. Hence we can call wait(),
notify() and notifyAll() methods only from synchronized area otherwise we will
get runtime exception saying IllegalMonitorStateException.
Once a Thread calls wait() method on the given object 1st it releases the lock of
that object immediately and entered into waiting state.
Once a Thread calls notify() (or) notifyAll() methods it releases the lock of that
object but may not immediately.
Except these (wait(),notify(),notifyAll()) methods there is no other place(method)
where the lock release will be happen.
Once a Thread calls wait(), notify(), notifyAll() methods on any object then it
releases the lock of that particular object but not all locks it has.
1. public final void wait()throws InterruptedException
2. public final native void wait(long ms)throws InterruptedException
3. public final void wait(long ms,int ns)throws InterruptedException
4. public final native void notify()
5. public final void notifyAll()
// Producer and Consumer Problem
import [Link];
import [Link];
class Data
Queue<String> q;
int capacity;
Data(int capacity)
q=new LinkedList<>();
[Link]=capacity;
}
public void publish(String msg) throws InterruptedException
String name=[Link]().getName();
synchronized(this)
if([Link]()==capacity)
[Link]("Queue is Full "+name+" waiting for
message to consumed....!");
notify();
wait();
[Link](msg);
[Link]("Message Published: "+msg);
[Link]("Queru: "+q);
[Link]();
public void cosume() throws InterruptedException,IllegalMonitorStateException
String name=[Link]().getName();
synchronized(this)
if([Link]()==0)
[Link](name+" waiting for message");
notify();
wait();
String msg=[Link]();
[Link](name+" has consumed msg: "+msg);
[Link]("Queue: "+q);
//notify();
[Link]();
class Producer implements Runnable
final String[] messages={"Hi!!", "How are you!!", "I love you!", "What's going on?!!",
"That's really funny!!"};
Data data;
Producer(Data data)
[Link]=data;
public void run()
int i=0;
try
{
while(true)
[Link](1000);
[Link](messages[i]);
i=(i+1)%[Link];
catch(InterruptedException e)
class Consumer implements Runnable
Data data;
Consumer(Data data)
[Link]=data;
public void run()
try
while(true)
{
[Link](2000);
[Link]();
catch(InterruptedException e){}
class Test
public static void main(String[] args)
Data data=new Data(5);
Thread p=new Thread(new Producer(data),"producer");
Thread c=new Thread(new Consumer(data),"cosumer");
[Link]();
[Link]();