Multi Threading Shrikant
Multi Threading Shrikant
Multi Threading Shrikant
Example:
class ThreadDemo
{
public static void main(String[] args)
{
MyThread t=new MyThread();//Instantiation of a
Threadt.start();//starting of a Thread
for(int i=0;i<5;i++)
{
System.out.println("main thread");
}
}
}
Output:
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
main thread
main thread
main thread
main thread
main thread
No arg method
start
method
main
method
Example 1:
Example 2:
Output:
Case 8: life cycle of the Thread:
Diagram:
• Once we created a Thread object then the Thread is
said to be in new state or born state.
• Once we call start() method then the Thread will
be entered into Ready or Runnable state.
• If Thread Scheduler allocates CPU then the Thread will
be entered into running state.
• Once run() method completes then the Thread will entered into
dead state.
Case 9:
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():
Case 2: t1.run():
Case 3: t2.start():
Case 4: t2.run():
Case 6: r.run():
Output:
main
methodrun
method
Methods:
1. public final String getName()
2. public final void setName(String name)
Example:
class MyThread extends Thread
{}
class ThreadDemo
{
public static void main(String[] args)
{
System.out.println(Thread.currentThread().getName());//ma
inMyThread t=new MyThread();
System.out.println(t.getName());//Thread-0
Thread.currentThread().setName("Bhaskar Thread");
System.out.println(Thread.currentThread().getName());//Bhaskar
Threa
}
d
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_PRIORITY1
2. Thread. MAX_PRIORITY10
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
• The allowed values are 1 to 10 otherwise we will get
runtime exception saying
"IllegalArgumentException".
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().getPriority());//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");
}
}
}
Output:
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
main thread
main
thread
main
thread
main
thread
main
thread
main
thread
main
thread
main
thread
main
thread
main
thread
1. yield();
2. join();
3. sleep();
yield():
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
Note : Some operating systems may not provide proper support for
yield() method.
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:
Thread.sleep(2000);
}
catch (InterruptedException e){}
}
}
}
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");
}
}
}
Example:
class MyThread extends Thread
{
static Thread mt;
public void run()
{
try
{
mt.join();
}
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
ThreadChild
ThreadChild
ThreadChild
ThreadChild
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:
Example:
class ThreadJoinDemo
{
public static void main(String[] args)throws InterruptedException
{
}
}
Output:M
EGA
S out.println("M");
y Thread.sleep(3000);
s System.out.println("E");
t Thread.sleep(3000);
e System.out.println("G");
m Thread.sleep(3000);
. System.out.println("A");
Interrupting a Thread:
Note:
Example:
class MyThread extends 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
Example:
class Display
{
public synchronized void wish(String name)
{
for(int i=0;i<5;i++)
{
System.out.print("good
morning:");try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{}
System.out.println(name);
}
}
}
class MyThread extends Thread
{
Display d;
String
name;
MyThread(Display d,String name)
{
this.d=d;
this.name=nam
e;
}
public void run()
{
d.wish(name);
}
}
class SynchronizedDemo
{
public static void main(String[] args)
{
Display d1=new Display();
MyThread t1=new
MyThread(d1,"dhoni"); MyThread
t2=new MyThread(d1,"yuvaraj");
t1.start();
t2.start();
}
}
Case 1:
Diagram:
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
normal synchronized methods, normal static
methods, and normal instance methods
simultaneously.
5. Class level lock and object lock both are different
and there is no relationship between these two.
Synchronized block:
Example:
Int x=b;
Synchronized(x){}
Output:
Compile time error.
Unexpected type.
Found: int
Required:
reference
Questions:
Metho Is Thread
d Releases Lock?
yield() No
join() No
sleep() No
wait() Yes
notify() Yes
notifyA Yes
ll()
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();
System.out.println("main Thread got notification call");//step-4
System.out.println(b.total);
}
}
}
class ThreadB extends Thread
{
int total=0;
public void run()
{
synchronized(this)
{
System.out.println("child thread starts calcuation");//step-2
for(int i=0;i<=100;i++)
{
total=total+i;
}
System.out.println("child thread giving notification call");//step-
3
this.notify();
}
}
}
Output
:
Example 2:
Example:
Notify vs notifyAll():
Exampl
e: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");
}
}
class DeadLock implements Runnable
{
A a=new
A();B b=new
B();
DeadLock()
{
Thread t=new
Thread(this);t.start();
a.foo(b);//main thread
}
public void run()
{
b.bar(a);//child thread
}
public static void main(String[] args)
{
new DeadLock();//main thread
}
}
Output:
Thread1 starts execution of foo() method
Thread2 starts execution of bar() method
Thread2 trying to call a.last()
Thread1 trying to call b.last()
//here cursor always waiting.
Example:
Garbage collector
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
77
When ever the program runs with low memory the JVM will
execute Garbage Collector to provide free memory. So that
the main Thread can continue it's execution.
Example:
class MyThread extends Thread
{
class DaemonThreadDemo
{
public static void main(String[] args)
{
System.out.println(Thread.currentThread().isDaemon()
);MyThread t=new MyThread();
System.out.println(t.isDaemon()); 1
t.start();
t.setDaemon(true)
;
System.out.println(t.isDaemon());
}
}
Output
: false
false
RE:IllegalThreadStateExceptio
nExample:
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
:
Deadlock vs Starvation:
RACE condition:
ThreadGroup:
g.stop();
ThreadLocal(1.2 v):
GreenThread:
1. GreenThread Model
2. Native OS Model
GreenThread Model
Native OS Model
Example:
Class MyClass extends Frame,Thread//invalid
If we write implements Runnable still there is a scope
to extend one more class. Example:
1. class MyClass extends Thread implements Runnable
2. class MyClass extends Frame implements Runnable
How can you stop a Thread which is running?
Questions:
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?