Java Multitherding
Java Multitherding
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86,
80 96 96 96 96, 9246212143 | www.durgasoft.com 1|Page
JAVA Means DURGASOFT
Multi Threading
Information about multithreading:-
1) The earlier days the computer’s memory is occupied only one program after completion of one
program it is possible to execute another program is called uni programming.
2) Whenever one program execution is completed then only second program execution will be
started such type of execution is called co operative execution, this execution we are having lot
of disadvantages.
a. Most of the times memory will be wasted.
b. CPU utilization will be reduced because only program allow executing at a time.
c. The program queue is developed on the basis co operative execution
To overcome above problem a new programming style will be introduced is called multiprogramming.
Advantages of multiprogramming:-
Thread:-
1) Thread is nothing but separate path of sequential execution.
2) The independent execution technical name is called thread.
3) Whenever different parts of the program executed simultaneously that each and
every part is called thread.
4) The thread is light weight process because whenever we are creating thread it is not
occupying the separate memory it uses the same memory. Whenever the memory is
shared means it is not consuming more memory.
5) Executing more than one thread a time is called multithreading.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86,
80 96 96 96 96, 9246212143 | www.durgasoft.com 2|Page
JAVA Means DURGASOFT
In the above program only one thread is available is called main thread to know the name of
the thread we have to execute the fallowing code.
The main important application areas of the multithreading are
1. Developing video games
2. Implementing multimedia graphics.
3. Developing animations
Example :-
class MyThread extends Thread//defining a Thread
{ //business logic of user defined Thread
public void run()
{ for (int i=0;i<10;i++)
{ System.out.println("userdefined Thread");
}
}
};
class ThreadDemo
{ public static void main(String[] args) //main thread started
{ MyThread t=new MyThread(); //MyThread is created
t.start(); //MyThread execution started
//business logic of main Thread
for (int i=0;i<10;i++)
{ System.out.println("Main Thread");
}
}
};
Flow of execution:-
1) Whenever we are calling t.start() method then JVM will search start() method in the MyThread
class since not available so JVM will execute parent class(Thread) start() method.
Thread class start() method responsibilities
a. User defined thread is registered into Thread Scheduler then only decide new Thread is
created.
b. The Thread class start() automatically calls run() to execute logics of userdefined Thread.
Thread Scheduler:-
Thread scheduler is a part of the JVM. It decides thread execution.
Thread scheduler is a mental patient we are unable to predict exact behavior of Thread
Scheduler it is JVM vendor dependent.
Thread Scheduler mainly uses two algorithms to decide Thread execution.
1) Preemptive algorithm.
2) Time slicing algorithm.
We can’t expect exact behavior of the thread scheduler it is JVM vendor dependent. So we
can’tsay expect output of the multithreaded examples we can say the possible outputs.
Preemptive scheduling:-
In this highest priority task is executed first after this task enters into waiting state or dead state
then only another higher priority task come to existence.
Ready :- t.start()
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.
First approach:-
important point is that when extending the Thread class, the sub class cannot extend any
other base classes because Java allowsonlysingle inheritance.
Second approach:-
1) Implementing the Runnable interface does not give developers any control over the thread
itself, as it simply defines the unit of work that will be executed in a thread.
2) By implementing the Runnable interface, the class can still extend other base classes if
necessary.
Creating two threads by extending Thread class using anonymous inner classes:-
class ThreadDemo
{ public static void main(String[] args)
{ Thread t1 = new Thread() //anonymous inner class
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86,
80 96 96 96 96, 9246212143 | www.durgasoft.com 7|Page
JAVA Means DURGASOFT
class ThreadDemo
{ public static void main(String[] args)
{ MyThread t=new MyThread();
t.start();
for (int i=0;i<5;i++ )
{ System.out.println("main thread");
}
}
}
Note :- If we are overriding start() method then JVM is executes override start() method at this
situation we are not giving chance to the thread class start() hence n new thread will be created only
one thread is available the name of that thread is main thread.
class MyThread extends Thread
{ Public void start()
{ System.out.println(“override start method”);
}
}
class ThreadDemo
{ public static void main(String[] args)
{ MyThread t=new MyThread();
t.start();
for (int i=0;i<5 ;i++ )
{ System.out.println("main thread");
}
}
}
Different Threads are performing different tasks:--
1) Particular task is performed by the number of threads here number of threads(t1,t2,t3) are
executing same method (functionality).
2) In the above scenario for each and every thread one stack is created. Each and every
method called by particular Thread the every entry stored in the particular thread stack.
class ThreadDemo
{ public static void main(String[] args) //1- main Thread
{ MyThread1 t1 = new MyThread1();
MyThread2 t2 = new MyThread2();
MyThread3 t3 = new MyThread3();
t1.start(); //2
t2.start(); //3
t3.start(); //4
}
};
Here Four Stacks are created
Main -----------stack1
t1---------------stack2
t2--------------stack3
t3-------------stack4
Multiple threads are performing single task:-
class MyThread extends Thread
{ public void run()
{ System.out.println("Sravyasoft task");
}
}
class ThreadDemo
{ public static void main(String[] args)//main Thread is started
{ MyThread t1=new MyThread(); //new Thread created
MyThread t2=new MyThread(); //new Thread created
MyThread t3=new MyThread(); //new Thread created
t1.start(); //Thread started
t2.start(); //Thread started
t3.start(); //Thread started
}
}
}
class ThreadDemo
{ public static void main(String args[])
{ MyThread t1=new MyThread();
MyThread t2=new MyThread();
System.out.println("t1 Thread name="+t1.getName());
System.out.println("t2 Thread name="+t2.getName());
System.out.println(Thread.currentThread().getName());
t1.setName("ratan");
System.out.println("after changeing t1 Thread name="+t1.getName());
}
}
Thread Priorities:-
1. Every Thread in java has some property. It may be default priority provided be
the JVM orcustomized 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. Thread defines the following constants to represent some standard priorities.
5. Thread Scheduler will use priorities while allocating processor the thread which
is havinghighest priority will get chance first and the thread which is having low
priority.
6. If two threads having the same priority then we can’t expect exact execution
order it dependsupon Thread Scheduler.
7. The thread which is having low priority has to wait until completion of high
priority threads.
8. Three constant values for the thread priority.
a. MIN_PRIORITY = 1
b. NORM_PRIORITY = 5
c. MAX_PRIORITY = 10
Thread class defines the following methods 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
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86,
80 96 96 96 96, 9246212143 | www.durgasoft.com 12 | P a g e
JAVA Means DURGASOFT
Thread priority decide when to switch from one running thread to another this process is called
context switching.
Java.lang.Thread.yield():-
Yield() method causes to pause current executing Thread for giving the chance for
waitingthreads of same priority.
If there are no waiting threads or all threads are having low priority then the same
thread willcontinue its execution once again.
Syntax:-
Public static native void yield();
Ex:
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86,
80 96 96 96 96, 9246212143 | www.durgasoft.com 13 | P a g e
JAVA Means DURGASOFT
Java.lang.Thread.join(-,-)method:-
Join method allows one thread to wait for the completion of another thread.
o t.join(); ---> here t is a Thread Object whose thread is currently running.
Join() is used to stop the execution of the thread until completion of some other Thread.
if a t1 thread is executed t2.join() at that situation t1 must wait until completion of the t2
thread.
public final void join()throws InterruptedExcetion
Public final void join(long ms)throws InterruptedException
Public final void join(long ms, int ns)throws InterruptedException
Methods of Thread class:-
class MyThread extends Thread
{ public void run()
{ for (int i=0;i<5;i++)
{ try{ Thread.sleep(2000); }
catch(InterruptedException e)
{e.printStackTrace();
}
System.out.println(i);
}
}
};
class ThreadDemo
{ public static void main(String[] args)
{ MyThread t1=new MyThread();
MyThread t2=new MyThread();
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86,
80 96 96 96 96, 9246212143 | www.durgasoft.com 14 | P a g e
JAVA Means DURGASOFT
Java.lang.Thread.Interrupted():-
A thread can interrupt another sleeping or waiting thread. But one thread is able to
interrupted only another sleeping or waiting thread.
To interrupt a thread use Thread class 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++ )
{ System.out.println("i am sleeping ");
Thread.sleep(5000);
}
}
catch (InterruptedException ie)
{ System.out.println("i got interupted by interrupt() call");
}
}
};
class ThreadDemo
{ public static void main(String[] args)
{ MyThread t=new MyThread();
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86,
80 96 96 96 96, 9246212143 | www.durgasoft.com 15 | P a g e
JAVA Means DURGASOFT
t.start();
t.interrupt();
}
};
No effect of interrupt() call:-
class MyThread extends Thread
{ public void run()
{ for (int i=0;i<10;i++ )
{ System.out.println("i am sleeping ");
}
}
};
class ThreadDemo
{ public static void main(String[] args)
{ MyThread t=new MyThread();
t.start();
t.interrupt();
}
};
NOTE:- The interrupt() is effected whenever our thread enters into waiting state or sleeping
state and if the our thread doesn’t enters into the waiting/sleeping state interrupted call will
be wasted.
Shutdown Hook:-
Shutdown hook used to perform cleanup activities when JVM shutdown normally or
abnormally.
Clean-up activities like
o Resource release
o Database closing
o Sending alert message
So if you want to execute some code before JVM shutdown use shutdown hook
The JVM will be shutdown in fallowing cases.
a. When you typed ctrl+C
b. When we used System.exit(int)
c. When the system is shutdown ……etc
To add the shutdown hook to JVM use addShutdownHook(obj) method of Runtime Class.
public void addShutdownHook(java.lang.Thread);
To remove the shutdown hook from JVM use removeShutdownHook(obj) method of Runtime
Class.
public boolean removeShutdownHook(java.lang.Thread);
To get the Runtime class object use static factory method getRuntime() & this method present
in Runtime class
Runtime r = Runtime.getRuntime();
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86,
80 96 96 96 96, 9246212143 | www.durgasoft.com 16 | P a g e
JAVA Means DURGASOFT
Factory method:- one java class method is able to return same class object or different class
object is called factory method.
Example :-
class MyThread extends Thread
{ public void run()
{System.out.println("shoutdown hook");
}
};
class ThreadDemo
{ public static void main(String[] args)throws InterruptedException
{ MyThread t = new MyThread();
//creating Runtime class Object by using factory method
Runtime r = Runtime.getRuntime();
r.addShutdownHook(t);//adding Thread to JVM hook
for (int i=0;i<10 ;i++)
{System.out.println("main thread is running");
Thread.sleep(3000);
}
}
};
D:\DP>java ThreadDemo
main thread is running
main thread is running
main thread is running
shoutdown hook
while running Main thread press Ctrl+C then hook thread will be executed.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86,
80 96 96 96 96, 9246212143 | www.durgasoft.com 17 | P a g e
JAVA Means DURGASOFT
Synchronized :-
Synchronized modifier is the modifier applicable for methods but not for classes andvariables.
If a method or a block declared as synchronized then at a time only one Thread is allowed
tooperate 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
isnever recommended to use.
The main purpose of this modifier is to reduce the data inconsistence problems.
Non-synchronized methods
void m1()
{ non-synchronized method any number of threads can access
}
Every thread accessing simultaneously
1) In the above case multiple threads are accessing the same methods hence we are getting data
inconsistency problems. These methods are not thread safe methods.
2) But in this case multiple threads are executing so the performance of the application will be
increased.
Synchronized methods
System.out.println(msg);
Thread.sleep(4000);
}
catch(Exception e)
{e.printStackTrace();}
}
}
class MyThread1 extends Thread
{ public void run(){Test.x("ratan");} };
class MyThread2 extends Thread
{ public void run(){Test.x("anu");} };
class MyThread3 extends Thread
{ public void run(){Test.x("banu");} };
class TestDemo
{ public static void main(String[] args)//main thread -1
{ MyThread1 t1 = new MyThread1();
MyThread2 t2 = new MyThread2();
MyThread3 t3 = new MyThread3();
t1.start(); //2-Threads
t2.start(); //3-Threads
t3.start(); //4-Threads
}
}
synchronized blocks:-
if the application method contains 100 lines but if we want to synchronized only 10 lines of code
use synchronized blocks.
The synchronized block contains less scope compare to method.
If we are writing all the method code inside the synchronized blocks it will work same as the synchronized
method.
Syntax:-
synchronized(object)
{ //code
}
class Heroin
{ public void message(String msg)
{ synchronized(this){
System.out.println("hi "+msg+" "+Thread.currentThread().getName());
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86,
80 96 96 96 96, 9246212143 | www.durgasoft.com 19 | P a g e
JAVA Means DURGASOFT
try{Thread.sleep(5000);}
catch(InterruptedException e){e.printStackTrace();}
}
System.out.println("hi Sravyasoft");
}
};
class MyThread1 extends Thread
{ Heroin h;
MyThread1(Heroin h)
{this.h=h;
}
public void run()
{ h.message("Anushka");
}
};
class MyThread2 extends Thread
{ Heroin h;
MyThread2(Heroin h)
{this.h=h;
}
public void run()
{ h.message("Ratan");
}
};
class ThreadDemo
{
public static void main(String[] args)
{ Heroin h = new Heroin();
MyThread1 t1 = new MyThread1(h);
MyThread2 t2 = new MyThread2(h);
t1.start();
t2.start();
}
};
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86,
80 96 96 96 96, 9246212143 | www.durgasoft.com 20 | P a g e
JAVA Means DURGASOFT
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.
When we create a thread in java that is user defined thread and f it is running JVM will not
terminate that process.
If a thread is marked as a daemon thread JVM does not wait to finish and as soon as all the user
defined threads are finished then it terminates the program and all associated daemon threads.
Set the daemon nature to thread by using setDaemon() method
o MyThread t = new Mythread();
t.setDaemon(true);
To know whether a thread is daemon or not use isDaemon() method
o Thread.currentThread().isDaemon();
class MyThread extends Thread
{ void message(String str)
{ try {
System.out.println("message="+str);
Thread.sleep(1000); }
catch (InterruptedException e)
{e.printStackTrace(); }
}
public void run()
{ if (Thread.currentThread().isDaemon())
{ while (true)
{ message("print hi ratan");
}
}
}
};
class ThreadDemo
{ public static void main(String[] args)
{ MyThread t = new MyThread();
t.setDaemon(true);//setting daemon nature to Thread
t.start();
try{Thread.sleep(5000);}
catch(InterruptedException e)
{e.printStackTrace();}
System.out.println("main thread completed");
}
};
Note :- in above example make the setdaemon() is comment mode then the program never terminates
even main thread finished it’s execution.
Volatile:-
Volatile modifier is also applicable only for variables but not for methods and classes.
If the values of a variable keep on changing such type of variables we have to declare
withvolatile modifier.
If a variable declared as a volatile then for every Thread a separate local copy will be created.
Every intermediate modification performed by that Thread will take place in local copy instead
of master copy.
Once the value got finalized just before terminating the Thread the master copy value will be
updated with the local stable value. The main advantage of volatile modifier is we can resolve
the data inconsistency problem.
But the main disadvantage is creating and maintaining a separate copy for every Thread
Increases the complexity of the programming and effects performance of the system.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86,
80 96 96 96 96, 9246212143 | www.durgasoft.com 22 | P a g e
JAVA Means DURGASOFT
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86,
80 96 96 96 96, 9246212143 | www.durgasoft.com 23 | P a g e