Mutithreading
Mutithreading
Agenda:
1. Introduction
2. The ways to define thread
01. By extending Thread class
02. By implementing Runnable(I)
3. Setting and Getting the name of the
thread
4. Thread Priorities
5. The methods to prevent method
execution as below:-
01. yeilds()
02. join()
03. sleep()
6. Synchronization
7. Inter Thread Communication
8. Deadlock
9. Daemen Thread
10. Conclusion
1. Introduction
-> Executing several task simultaneously, is the
concept of multi tasking. There are two types of
multi tasking:-
01. Process based Multi tasking
02. Thread based Multi tasking
01. Process based Multi tasking
->Executing several task simultaneously, where
each task is separate independent process, is called
Process based Multi tasking.
Ex-
While typing a java program in the editor, we
can able to listen mp3 audio songs, at the same
time we can download the file from internet. All
these tasks are executing simultaneously and
independent of each other and hence it is
process based multi tasking.
It is best suitable at OS level but not at
programmatic level.
//Defining a thread
public class MyThread extends Thread {
package com.sk.test2;
}
}
Case 1: Thread Schedular:
It is the part of the JVM, if mutiple threads
are waiting to get the chance for execution then
in which order they will execute , is decided by
Thread Schedular.
What is Algorithm followed by Thread
Schedular, we cant give any guarantee , it is
varied from JVM to JVM , Hence in which order
threads will be executed, we can’t give the
guirantee and hence we can’t aspect exact
output for multi threaded programs but we can
provide severall possible outputs.
The following are the various possible output
for the above program:-
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
………..
………..
Child Thread
Child Thread
Child Thread
………….
………….
Child Thread
Child Thread
Child Thread
………….
………….
………..
………..
Main Thread
Child Thread
Main Thread
Child Thread
………….
………….
Case 2:
Diff between t.start() and t.run()
In t.start(), a new thread will be started
But in the case of t.run(), no new thread will
be created and run() method will be executed
just like a normal method call by Main-Thread.
In the above program, if replace t.start() with
t.run() then output is :
Child Thread
Child Thread
Child Thread
………….
………(10 times)
Main Thread
Main Thread
Main Thread
………
………(10 times)
And total output is produced by only Main-Thread.
Case 3: Importance Thread Class start() method
Thread class start() method is the responsible to
do the following:-
01. Register our thread with ThreadScheduler
02. Other mandatory activities
03. Execute run method
Ex-
Start(){
01. Register our thread with ThreadScheduler
02. Other mandatory activities
03. Execute run method
}
Hence, without executing Thread class start() method,
there is no chance of starting a thread in java.
Hence, Thread class start() method acts as Heart of Multi
Threading.
Case 4: Overloading of run() method
Overloading of run() is possible but Thread class
start() method always call no-arg run() method only.
Case 5: If we are not Overriding run() method
If we are not overriding run() method then
Thread class run() method will be executed which
has empty implementation.
Hence we won’t get any output.
It is highly recommended run() in our class
otherwise don’t go for multi theading concept.
Case 6: If we are overriding start() method
If we are overriding a start() method then our
defined start() method will be executed just like
normal method call and new thread/ child thread
won’t be started.
As we are not giving to chance to Thread class
start() method , run() method won’t be executed.
package com.sk.test6;
//Defining a thread
public class MyThread extends Thread {
package com.sk.test6;
System.out.println("Main-Thread");
o/p:-
start() method
Main-Thread
//Defining a thread
public class MyThread extends Thread {
package com.sk.test7;
}
o/p:-(Three possible output)
start method start method start method
Main Thread run method run method
run method Main Thread Main Thread
Case 8:
Case 9:
After starting a thread, if we are trying to
restart same thread once again, then we will get
RE: IllegalThreadStateException
Ex-
Thread t=new Thread();
t.start();
………..
………..
t.start();//RE:IllegalThreadStateException
-> We can also define a thread by implementing an
inteface:
Pic:
Runnable Interface is available in java.lang
package and it cotains only one method whose
prototype as: Public void run();
Case Study:
MyRunnable mr=new MyRunnable();
Thread t1=new Thread();
Thread t2=new Thread();
Case 1:
Q1. In which of the above cases a new thread will
be created ?
T1.start() and T2.start();
Q2. In which of the above cases , a new thread
started which is the responsible for the execution of
MyRunnable class run() method ?
Ans. T2.start();
Q3. In which of the above cases , MyRunnable class
run() method is executed ?
T2.start(), t2.run() and mr.run().
Q4. Which is the best way to define a Thread ?
Ans. Among two ways of defining a thread ,
implements Runnable approach(2nd approach) is
recommended .
In the First Approach, our class always
extends the Thread class and hence there is no
chance of extending any other class, due to this
we are missing inheritence benefits.
But in the 2nd approach while implementing
Runnable Interface, we can extends any other
class and hence we won’t miss any Inheritence
benefits.
Because of above reason, we can conclude
implements Runnable approach(2nd approach) is
recommended to use.
Ex-
Program:
package com.sk.test3;
package com.sk.test3;
public class ThreadDemo extends Thread{
}
}
package com.sk.test3;
package com.sk.test3;
public class ThreadDemo extends Thread{
public static void main(String[] args) {
mt.start();
for(int i=0;i<10;i++){
System.out.println("Main-Thread");
}
03. sleep(-)
-> If a thread don’t want to perform some
operations for particular amount of time then
we should go for sleep() method.
-> Prototype:
public static native void sleep(long ms) throws
IntrruptedException
public static void sleep(long ms,int ns) throws
IntrruptedException
Q. How a thread interrupted to another
thread?
Ans: A thread can interrupt a sleeping or
waiting thread by using interrupt() method of
Thread class.
public void interrupt();
Ex-
In the above example, Main-Thread
interrupts Child-Thread.
Note:
Whenever we call interrupt() method, If
the target thread is not in sleeping or
waiting state then there is no impact of
interrupt() method call immediately.
Interrupt() method call will wait until
enter into sleeping or waiting state.
If the target thread entered into waiting
or sleeping state then interrupt() call will
interrupt to that thread.
If target thread never entered sleeping or
waiting state in its life time then, then only
interrupt() call will be wasted.
In the above program interrupt() call
waited until child thread completing for
loop 1000 times.
Saturday, March 21, 2015
Comparison between
yield() ,join() and sleep():-
Property Yield() Join() Sleep()
Purpose It causes If a If a thread
to pause thread don’t want
current wants to to perform
executing wait until any
thread to completin operation
give the g some for
chance other apartincaula
for thread r amount of
remainin then we time ie just
g waiting should go pausing is
of same for join required
priority
Is it staticYes No Yes
method?
Is It final No Yes No
method?
Is it No Yes Yes
overloade
d or not?
Is it No Yes Yes
throws IE?
Is it native Yes No Sleep(long
method? ms)->native
Sleep(long,in
t ns)->non-
native
Daemon Thread
->The threads which are executing in the
background are called Daemon thread.
-> Garbage collector
-> The main objective of Daemon thread is to
provide support for non-Daemon threads (like
main-thread).
->For Example, if main-thread runs with low
memory then jvm runs Daemon-Thread Gc then
GC destroys useless objects and provide some
free memory so that main-thread can continue
its execution without any problems.
Real Time Example:-
It is just like Producer, Director , Camera
man and other members while Hero,
heroins are acting in a movie.
Usually Daemon runs with low priority
but based on our requirement they can
with high priority also.
We can check whether thread is Daemon
or not by using isDaemon() method of
Thread class.
Public boolean isDaemon();
We can change daemon nature of a
thread by using setDaemon(-) of Thread
class.
Public void setDaemon(boolean b);
But we can change the daemon nature of
a thread before starting of a thread only
that is once thread is started, we can’t
change its daemon nature otherwise we will
get RE: IllegalThreadStateException.
Default Nature of Daemon Thread
->By default main-thread is non-daemon but all
remaining daemon nature is inheriting from
parent to child that is if the parent thread is
daemon then child thread is also daemon and if
parent thread is not daemon then child thread
is also not daemon.
Ex1-
-> Whenever last non-daemon threads
terminate the automatically all daemon threads
also will be terminate with respect to their
position.
Ex2-
Note:-
It is impossible to change daemon nature
of main-thread because it is already started
by jvm at beginning only.
Synchronization
Synchronization is the keywords which is
only applicable for method and blocks but
not for classes and variables.
If multiple threads are operating
simultaneously on the same java object
then there may be a chance data
inconsistence, this is called RACE condition.
We can solve this problem using
synchronized keyword.
If a method or block declared as
synchronized then at a time only one thread
is allowed to execute that method or block
on the given object.
As threads are executing one by one ,
data inconsistency problem will be solved
automatically.
The main disadvantage of synchronized
keyword is increases waiting time of the
threads and creates performance problems;
hence if there is no specific requirement
then it is not recommended to use
synchronized keyword.
Real Time Example:
01. Dogs
02. Sweets
03. Bank
Internally synchronization concept is
implemented using lock concept.
Whenever we are using synchronized
keyword then only lock concept comes into
the picture.
If a thread wants to execute synchronized
method on the given object; first it has to
get lock of the object. Once thread got a
lock then it is allowed to execute any
synchronized method on the given object.
Once synchronized method execution
completes, automatically thread releases
the lock.
Acquiring and releasing the lock takes
care by JVM and programmer not required
to do anything.
While a thread executing synchronized
method on the given object the remaining
threads are not allowed to execute any
synchronized method on that object
simultaneously but remaining threads are
allowed to execute any non-synchronized
method simultaneously.
Class X{
synch m1()
Synch m2()
M3()
}
T1 wants to execute m1()
T2 came for m1 --X
T3 cam for m3 ---Ok
Note:
Pic scjp13:
Every object in java has a unique lock.
Lock concept is defined based on object
but not based on method.
Inside a method, if we are performing any
update operation and the state of
application (or) object is changing then that
method should be declared as
synchronized.
Inside a method, jus we are performing
read operation and application/object
won’t be change then that method should
be declared non-synchronized.
Ex1-
Banking Application
In the Banking application, withdraw
operation changing state of application and
should be performed by only one thread at
a time on the given the account object.
Hence it should be synchronized.
balance_Enquiry() won’t perform any
update operations and can be executed by
multiple threads simultaneously ; hence it
should be non-synchronized.
Ex2:-
Reservation System
check_ Availability() of ticket won’t
perform any update operation and it is just
read operation and hence this method
should be non-synchronized.
book_Tickets() method performs update
operations and hence this method should
be perform by only one thread at a time;
hence it should be synchronized.
Ex-
Program (sync2):
if wish method is not synchronized then
both threads will be executed
simultaneously and hence we will get
irregular output.
Output:
Good Moring: Good Morning
Dhoni
Good Morning
if we declare wish method as
synchronized then only one thread is
allowed to execute that method on the
given object ; hence we will get regular
output.
Output:
Good Morning:Dhoni
Good Morning:Dhoni
Good Morning:Dhoni
Good Morning:Raina
Good Morning:Raina
Good Morning:Raina
Case Study:
Display d1=new Display();
Display d2=new Display();
MyThread mt1=new MyThread(d1,”Dhoni”);
MyThread mt2=new MyThread(d1,”Raina”);
mt1.start(); mt2.start();
pic scjpsync1:
Even though wish method is synchronized
then also we will get irregular output
because both thread will be executed on
different Display objects simultaneously.
Note:
If multiple threads are operating on
multiple java objects then synchronization
is not required.
If multiple threads are operating on same
java object then synchronization is
required.
Class level Lock
Every class in java has unique lock which
is also class level lock.
If a thread wants to execute static
synchronized method ; first it has to get
class level lock; if Thread got class level then
it is allowed to execute any static
synchronized method.
Once method execution completes
automatically , thread releases the lock.
Q-> why a thread is executing static
synchronized method then the remaining
threads are not allowed to execute any
static method of that class simultaneously;
But remaining threads are allowed to
execute simultaneously:-
1)nonsynchronized static method
2)Synchronized instance method
3)Nonsynchronized instance method
Ex-
Class x{
Static synch m1()
Static synch m2()
Static m3()
Synch m4()
m5()
}
Pic scjpsync2:
Synchronized block:
->If very few lines of the code require
synchronization then it is not recommended to
declare entire method as synchronized.
-> We have to declare those few lines of the
code by using synchronized block.
-> The main advantage of synchronized block
over synchronized method is performance will
be improved by reducing waiting time of
threads.
-> We can synchronized block as follows:
a) To get lock of current object:-
Ex-
Synchronized(this){
…………..
…………..
}
If a thread got lock of current object then
only it is allowed to execute this area.
b) To get lock of a particular object
Ex-
Synchronized(b){
…………
………….
}
If a thread got lock of ‘b’ object then only
it is allowed to execute this area.
c) To get class level lock
Ex-
Synchronized(Display.class){
}
If a thread got class level lock then only it
is allowed to execute its block.
Note:
Lock concept available only for object and
classes but not for primitive hence we can’t
pass primitive type as argument to
synchronized block otherwise we will get
compile time error saying unexpected type
Found: int required : required
Ex-
Int x=10;
Synchronized(x){…………….}
FAQ1. What is the synchronized keyword and
where we can apply?
FAQ2: Explain advantage of synchronized
keyword?
FAQ3: Explain disadvantage of synchronized
keyword?
FAQ4: What is RACE condition?
FAQ5: What is Object lock and when it is
required?
FAQ6: What is class level and when it is
required?
FAQ7: What is difference between class level
lock and object level lock?
FAQ8: Why a the thead executing synchronized
method and any onject is the remaining thread
are allowed to execute ?;;;;;;;;corection
Ans: No
FAQ10: What is synchronized block ? Explain
advantage block over synchronized method?
11. Explain the difference between
synchronized block and synchronized method?
12. Is a thread required multiple locks
simultaneously ?
Ans: yes from different object.
Ex-
Class y{
public synch void m1(){
X x=new X();
Synchronized(x){
………………
………………
}
}}
Y y=new Y();
y.m1();
To reach this area thread required two
locks of X and Y.
14. What is synchronized statement?
Ans. Interview people created terminology
The statements which are present in
synchronized block or synchronized
method; called synchronized statement.
Ex-(Pic incom3):
Ex-Program:
package com.sk.test3;
int tot=0;
synchronized(this){
tot+=i;
}
}
package com.sk.test3;
mt.start();
synchronized(mt){
System.out.println("Main thread calling wait method");
mt.wait();
System.out.println("Total result:"+mt.tot);
}
/*
output:
Main thread calling wait method
Child thread starts calculation
Child thread giving notification
Main thread got notification
Total result:5050
*/
Java.util.cuncurrent package
The problems with synchronized
keywords are:-
01. If a thread releases the lock then which
waiting thread will get the lock, we are
not having control on this.
02. We can’t specify maximum waiting for a
thread to get a lock so that it will wait
until getting lock which may create
performance problems and which may
cause deadlock.
03. We are not having any flexibility to try
for a lock without waiting.
04. There is no API to list out all waiting
thread for a lock.
05. The synchronized keyword, we have to
use only within a method and not
possible to declare across multiple
methods.
To overcome from above problem SUN
people introduced java.util.concurrent.locks
package in jdk1.5v and it also provides
several enhancement to the programmer to
more control on concurrency.
Lock(I)
Lock object is similar to implicit thread
acquired by a thread to execute
synchronized method or synchronized
block.
Lock implementation provides more
flexibility and extensive operations to the
programmer then traditional implicit lock.
Important methods of Lock(I):-
01. Void lock()
To get the lock.
If the lock is available immediately thread
will get that lock.
If the lock is not available then thread will
wait until getting that lock; this behavior is
exactly implicit lock.
02. Boolean tryLock()
To acquire the lock it is available then the
thread acquires lock and return true.
If the lock is not available then this
method return false and continue its
execution without waiting; in this case
thread never be blocked.
If(l.tryLock()){ perform some safe
operations}
Else{perform some alternative operations}
03. Boolean tryLock(long time, TimeUnit
unit)
To acquire the lock if is available then
immediately that thread will get that lock
and if the lock is not available then the
thread will wait until specified amount of
time ,still if the thread’s lock is not available
then the thread continue its execution.
Ex-
If(l.tryLock(1000,TimeUnit.MILLISECONDS))
{}else{}
TimeUnit
It is a enum presenti
java.util.concucurrent package
Ex-
Enum TimeUnit{
NANOSECONDS;
MICROSECONDS;
MILLISECONDS;
SECONDS;
MINUTES
SECONDS
04. Void interruptly()
While locks interruptly acquire the
available; if the lock is not available then It
will wait.
While waiting if it is interrupted then the
thread won’t the lock.
05. Void Unlock()
To unlock the locks
The call the unlock() method compulsory
current thread should be owner of that
thread otherwise we will get compiler time
error saying IllegalMonitorException.
ReentrantLock(C)
It implements Lock(I).
It is the direct child class of the object
class.
Reentrant means a thread can acquire
same lock multiple times without any
issues.
Internally ReentrantLock increment
threads personal; whenever we call unlock
and lock will be release whenever count
reaches zero.
Constructor
01. ReentrantLock rl=new ReentrantLock()
Creates a new lock.
02. ReentrantLock rl=new
ReentrantLock(boolean fairness)
Creates a new lock with specified fairness
policy.
If fairness is true then longest waiting
thread can get the lock if it is available that
is it follows FCFS(First comes first server).
If fairness is false then we can’t expect
which waiting .
If we are not setting then default value is
false.
Q. which of the following are eqals:
01. ReentrantLock rl=new ReentrantLock();
02. ReentrantLock rl=new
ReentrantLock(true);
03. ReentrantLock rl=new
ReentrantLock(false) ;
Method of ReentrantrantLock
01. Void lock()
02. Boolean tryLock()
03. Boolean tryLock(long l,TimeUnit t)
04. Void lockInterruptly()
05. Void unlock()
Other Methods are:-
01. Int getHoldCount()
Returns the no. of holds on this lock by
current .
02. Boolean isHeldByCurrentThread()
Return true if only if if lock is held by
current thread.
03. Int getQueueLength()
Return the no. of the lock waiting for the
lock.
04. Collection of thread which are waiting
to get the lock
05. Boolean hasqueuedThread()
06. Boolean isLocked()
If the lock is acquired by some thread.
07. Boolean isFair()
Returns true if the lock object is fair.
08. Thread getOwner()
Returns the thread which acquire the
lock.
Sunday, 29 March, 2015
Ex-
Import java.util.concurrent.locks.*;
Public class ReentrantLock2{
Public static void main(String[] args){
ReentrantLock I=new ReentrantLock();
l.lock(); l.lock();
Sopln(l.isLocked());//true
Sopln(l.isHeldByCurrentThread());//true
Sopln(l.getQueueLength())//0
l.unlock();
Sopln(l.getHoldCount());//1
Sopln(l.isLocked());//true
l.unlock();
Sopln(l.isLocked());//false
Sopln(l.isFair())//false
}}
Ex-Program:
package com.sk.reentrant1;
import java.util.concurrent.locks.ReentrantLock;
}
package com.sk.reentrant1;
package com.sk.reentrant1;
}
}
import java.util.concurrent.locks.ReentrantLock;
import com.sk.reentrant1.Display;
}
package com.sk.reentrant2;
}
}
//output
Yuvrajgot the lock and performing the safe oprations.
Dhoni unable to get the lock and perfroming some
alternative operations
Ex-Program for tryLock with time period
package com.sk.reentran3;
import java.util.concurrent.TimeUnit;
import
java.util.concurrent.locks.ReentrantLock
;
import com.sk.reentrant1.Display;
public class MThread extends Thread {
static ReentrantLock l=new
ReentrantLock();
MThread (String name){
super(name);
}
public void run(){
do{
try{
if(l.tryLock(5000,TimeUnit.MICROSECON
DS)){
System.out.println(Thread.currentThrea
d().getName()+"got the lock and
performing the safe oprations.");
Thread.sleep(3000);
l.unlock();
break;
}
else{
System.out.println(Thread.currentThrea
d().getName()+" unable to get the lock
and perfroming some alternative
operations");
}
}catch(Exception ex){}
}while(true);}}
package com.sk.reentran3;
public class ReentrantLockDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
MThread t1=new MThread("Dhoni");
MThread t2=new MThread("Yuvraj");
t1.start();
t2.start();
}
//output
Dhoni unable to get the lock and perfroming some
alternative operations
Dhoni unable to get the lock and perfroming some
alternative operations
Dhoni unable to get the lock and perfroming some
alternative operations
Dhoni unable to get the lock and perfroming some
alternative operations
Dhoni unable to get the lock and perfroming some
alternative operations
Dhoni unable to get the lock and perfroming some
alternative operations
Dhoni unable to get the lock and perfroming some
alternative operations
Dhoni unable to get the lock and perfroming some
alternative operations
Dhoni unable to get the lock and perfroming some
alternative operations
Dhoni unable to get the lock and perfroming some
alternative operations
Dhoni unable to get the lock and perfroming some
alternative operations
Dhoni unable to get the lock and perfroming some
alternative operations
Dhoni unable to get the lock and perfroming some
alternative operations
Dhoni unable to get the lock and perfroming some
alternative operations
Dhoni unable to get the lock and perfroming some
alternative operations
Dhoni unable to get the lock and perfroming some
alternative operations
Dhonigot the lock and performing the safe oprations.
Constructor
InheritableThreadLocal tl=new
InheriatableThreadLocal();
InheritableThreadLocal is the child class
of ThreadLocal and hence all the methods
present in the thread local by default
available to InheritableThreadLocal.
In addition to these method if contains
only one new method as below:
Public Object childValue(Object
parentValue);
Ex-
Prg3:
In the above if we replace
InheritableThreadLocal with ThreadLocal
and if we are not overriding child value
method then the output is:
parentThead valuepp
childthread value->null
If in the above if we are maintaining
inheriatableThreadLocal and we are not
overriding childValue() method then
Output:
parentThread value is: pp
childThread value: pp