Multi Threading
Multi Threading
com
Multi Threading
Agenda
1. Introduction.
2. The ways to define, instantiate and start a new
Thread.
1. By extending Thread class
2. By implementing Runnable interface
3. Thread class constructors
4. Thread priority
5. Getting and setting name of a Thread.
6. The methods to prevent(stop) Thread execution.
1. yield()
2. join()
3. sleep()
7. Synchronization.
8. Inter Thread communication.
9. Deadlock
10. Daemon Threads.
11. Various Conclusion
1. To stop a Thread
2. Suspend & resume of a thread
3. Thread group
4. Green Thread
5. Thread Local
12. Life cycle of a Thread
Introduction
class ThreadDemo
{
public static void main(String[] args)
{
MyThread t=new
MyThread();//Instantiation of a Thread
t.start();//starting of a Thread
for(int i=0;i<5;i++)
{
System.out.println("main thread");
}
}
}
}
public void run(int i)
{
System.out.println("int arg method");
}
}
class ThreadDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.start();
}
}
Output:
No arg method
t.start();
System.out.println("main method");
}
}
Output:
start method
main method
Entire output produced by only main Thread.
Note : It is never recommended to override start() method.
Case 7:
Example 1:
Example 2:
Output:
Diagram:
Example:
class ThreadDemo
{
public static void main(String[] args)
{
MyRunnable r=new MyRunnable();
Thread t=new Thread(r);//here r is a
Target Runnable
t.start();
for(int i=0;i<10;i++)
{
System.out.println("main thread");
}
}
}
Output:
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
child Thread
We can't expect exact output but there are several possible
outputs.
Case study:
MyRunnable r=new MyRunnable();
Thread t1=new Thread();
Thread t2=new Thread(r);
Case 1: t1.start():
A new Thread will be created which is responsible for the
execution of Thread class run()method.
Output:
main thread
main thread
main thread
main thread
main thread
Case 2: t1.run():
Case 3: t2.start():
New Thread will be created which is responsible for the
execution of MyRunnable run() method.
Output:
main thread
main thread
main thread
main thread
main thread
child Thread
child Thread
child Thread
child Thread
child Thread
Case 4: t2.run():
No new Thread will be created and MyRunnable run()
method will be executed just like a normal method call.
Output:
child Thread
child Thread
child Thread
child Thread
child Thread
main thread
main thread
main thread
main thread
main thread
Case 5: r.start():
We will get compile time error saying start()method is not
available in MyRunnable class.
Output:
Compile time error
E:\SCJP>javac ThreadDemo.java
ThreadDemo.java:18: cannot find symbol
Symbol: method start()
Location: class MyRunnable
Case 6: r.run():
No new Thread will be created and MyRunnable class
run() method will be executed just like a normal method
call.
Output:
child Thread
child Thread
child Thread
child Thread
child Thread
main thread
main thread
main thread
main thread
main thread
Diagram:
Output:
main method
run method
System.out.println(Thread.currentThread().ge
tName());//main
MyThread t=new MyThread();
System.out.println(t.getName());//Thread-0
Thread.currentThread().setName("Bhaskar
Thread");
System.out.println(Thread.currentThread().ge
tName());//Bhaskar Thread
}
}
Note: We can get current executing Thread object
reference by using Thread.currentThread() method.
Thread Priorities
• Every Thread in java has some priority it may be
default priority generated by JVM (or) explicitly
provided by the programmer.
• The valid range of Thread priorities is 1 to 10[but not
0 to 10] where 1 is the least priority and 10 is highest
priority.
• Thread class defines the following constants to
represent some standard priorities.
1. Thread. MIN_PRIORITY----------1
2. Thread. MAX_PRIORITY----------10
3. Thread. NORM_PRIORITY--------5
• There are no constants like
Thread.LOW_PRIORITY,
Thread.HIGH_PRIORITY
• Thread scheduler uses these priorities while
allocating CPU.
• The Thread which is having highest priority will get
chance for 1st execution.
• If 2 Threads having the same priority then we can't
expect exact execution order it depends on Thread
scheduler whose behavior is vendor dependent.
• We can get and set the priority of a Thread by using
the following methods.
1. public final int getPriority()
2. public final void setPriority(int
newPriority);//the allowed values are 1 to 10
Default priority:
The default priority only for the main Thread is 5. But for
all the remaining Threads the default priority will be
inheriting from parent to child. That is whatever the
priority parent has by default the same priority will be for
the child also.
Example 1:
class MyThread extends Thread
{}
class ThreadPriorityDemo
{
public static void main(String[] args)
{
System.out.println(Thread.currentThread().ge
tPriority());//5
Thread.currentThread().setPriority(9);
MyThread t=new MyThread();
System.out.println(t.getPriority());//9
}
}
Example 2:
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("child
thread");
}
}
}
class ThreadPriorityDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
//t.setPriority(10); //----> 1
t.start();
for(int i=0;i<10;i++)
{
System.out.println("main thread");
}
}
}
main thread
main thread
main thread
main thread
main thread
main thread
Some operating systems(like windowsXP) may not
provide proper support for Thread priorities. We have to
install separate bats provided by vendor to provide
support for priorities.
Example:
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
Thread.yield();
System.out.println("child
thread");
}
}
}
class ThreadYieldDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.start();
for(int i=0;i<5;i++)
{
System.out.println("main thread");
}
}
}
Output:
main thread
main thread
main thread
main thread
main thread
child thread
child thread
child thread
child thread
child thread
In the above program child Thread always calling yield()
method and hence main Thread will get the chance more
number of times for execution.
Hence the chance of completing the main Thread first is
high.
Join():
If a Thread wants to wait until completing some other
Thread then we should go for join() method.
Example: If a Thread t1 executes t2.join() then t1 should
go for waiting state until completing t2.
Diagram:
}
}
class ThreadJoinDemo
{
public static void main(String[] args)throws
InterruptedException
{
MyThread t=new MyThread();
t.start();
//t.join(); //--->1
for(int i=0;i<5;i++)
{
System.out.println("Rama Thread");
}
}
}
for(int i=0;i<5;i++)
{
System.out.println("Child
Thread");
}
}
}
class ThreadJoinDemo
{
public static void main(String[] args)throws
InterruptedException
{
MyThread mt=Thread.currentThread();
MyThread t=new MyThread();
t.start();
for(int i=0;i<5;i++)
{
Thread.sleep(2000);
System.out.println("Main Thread");
}
}
}
Output :
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Note :
If main thread calls join() on child thread object and child
thread called join() on main thread object then both
threads will wait for each other forever and the program
will be hanged(like deadlock if a Thread class join()
method on the same thread itself then the program will be
hanged ).
Example :
class ThreadDemo {
public static void main() throws
InterruptedException {
Thread.currentThread().join();
--------------- --------
main main
}
Sleep() method:
If a Thread don't want to perform any operation for a
particular amount of time then we should go for sleep()
method.
1. public static native void sleep(long ms) throws
InterruptedException
2. public static void sleep(long ms,int ns)throws
InterruptedException
Diagram:
Example:
class ThreadJoinDemo
{
public static void main(String[] args)throws
InterruptedException
{
System.out.println("M");
Thread.sleep(3000);
System.out.println("E");
Thread.sleep(3000);
System.out.println("G");
Thread.sleep(3000);
System.out.println("A");
}
}
Output:
M
E
G
A
Interrupting a Thread:
t.start();
//t.interrupt(); //--->1
System.out.println("end of main
thread");
}
}
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println("iam lazy
thread");
}
System.out.println("I'm entered
into sleeping stage");
try
{
Thread.sleep(3000);
}
catch (InterruptedException e)
{
System.out.println("i got
interrupted");
}
}
}
class ThreadInterruptDemo1
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.start();
t.interrupt();
System.out.println("end of main
thread");
}
}
Synchronization
1. Synchronized is the keyword applicable for methods
and blocks but not for classes and variables.
2. If a method or block declared as the synchronized
then at a time only one Thread is allow to execute
that method or block on the given object.
3. The main advantage of synchronized keyword is we
can resolve date inconsistency problems.
4. But the main disadvantage of synchronized keyword
is it increases waiting time of the Thread and effects
performance of the system.
5. Hence if there is no specific requirement then never
recommended to use synchronized keyword.
6. Internally synchronization concept is implemented
by using lock concept.
7. Every object in java has a unique lock. Whenever we
are using synchronized keyword then only lock
concept will come into the picture.
8. If a Thread wants to execute any synchronized
method on the given object 1st it has to get the lock
of that object. Once a Thread got the lock of that
object then it's allow to execute any synchronized
method on that object. If the synchronized method
execution completes then automatically Thread
releases lock.
9. While a Thread executing any synchronized method
the remaining Threads are not allowed execute any
synchronized method on that object simultaneously.
But remaining Threads are allowed to execute any
non-synchronized method simultaneously. [lock
37
[email protected]
Case study:
Case 1:
Display d1=new Display();
Display d2=new Display();
MyThread t1=new MyThread(d1,"dhoni");
MyThread t2=new MyThread(d2,"yuvaraj");
t1.start();
t2.start();
Diagram:
Questions:
1. Explain about synchronized keyword and its
advantages and disadvantages?
2. What is object lock and when a Thread required?
3. What is class level lock and when a Thread required?
4. What is the difference between object lock and class
level lock?
5. While a Thread executing a synchronized method on
the given object is the remaining Threads are allowed
to execute other synchronized methods
42
[email protected]
Diagram:
Diagram:
Diagram:
Example 1:
class ThreadA
{
public static void main(String[] args)throws
InterruptedException
{
ThreadB b=new ThreadB();
b.start();
synchronized(b)
{
System.out.println("main Thread calling
wait() method");//step-1
b.wait();
Example:
Notify vs notifyAll():
• We can use notify() method to give notification for
only one Thread. If multiple Threads are waiting then
only one Thread will get the chance and remaining
Threads has to wait for further notification. But
which Thread will be notify(inform) we can't expect
exactly it depends on JVM.
• We can use notifyAll() method to give the
notification for all waiting Threads. All waiting
Threads will be notified and will be executed one by
one, because they are required lock
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.
Example:
class A
{
public synchronized void foo(B b)
{
System.out.println("Thread1 starts
execution of foo() method");
try
{
Thread.sleep(2000);
}
catch (InterruptedException e)
{}
System.out.println("Thread1 trying to
call b.last()");
b.last();
}
public synchronized void last()
{
System.out.println("inside A, this is
last()method");
}
}
class B
{
public synchronized void bar(A a)
{
System.out.println("Thread2 starts execution
of bar() method");
try
{
Thread.sleep(2000);
}
catch (InterruptedException e)
{}
System.out.println("Thread2 trying to call
a.last()");
a.last();
}
public synchronized void last()
{
System.out.println("inside B, this is last()
method");
}
}
Daemon Threads:
The Threads which are executing in the background are
called daemon Threads.
class DaemonThreadDemo
{
public static void main(String[] args)
{
System.out.println(Thread.currentThread().is
Daemon());
MyThread t=new MyThread();
System.out.println(t.isDaemon());
1
t.start();
t.setDaemon(true);
System.out.println(t.isDaemon());
}
}
Output:
false
false
RE:IllegalThreadStateException
Example:
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("lazy thread");
try
{
Thread.sleep(2000);
}
catch (InterruptedException e)
{}
}
}
}
class DaemonThreadDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.setDaemon(true); //-->1
t.start();
System.out.println("end of main Thread");
}
}
Output:
End of main Thread
Deadlock vs Starvation:
• A long waiting of a Thread which never ends is
called deadlock.
condition
we can resolve race condition by using synchronized
keyword.
ThreadGroup:
Based on functionality we can group threads as a single
unit which is nothing but ThreadGroup.
ThreadLocal(1.2 v):
We can use ThreadLocal to define local resources which
are required for a perticular Thread like DBConnections,
counterVariables etc.,
1. What is a Thread?
2. Which Thread by default runs in every java
program?
Ans: By default main Thread runs in every java
program.
3. What is the default priority of the Thread?
4. How can you change the priority number of the
Thread?
5. Which method is executed by any Thread?
Ans: A Thread executes only public void run()
method.
6. How can you stop a Thread which is running?
7. Explain the two types of multitasking?
8. What is the difference between a process and a
Thread?
9. What is Thread scheduler?
10. Explain the synchronization of Threads?
11. What is the difference between synchronized
block and synchronized keyword?
12. What is Thread deadlock? How can you resolve
deadlock situation?
13. Which methods are used in Thread
communication?
14. What is the difference between notify() and
notifyAll() methods?
15. What is the difference between sleep() and
wait() methods?
16. Explain the life cycle of a Thread?
17. What is daemon Thread?
65