Thread life cycle and Preventing Thread execution
Preventing thread execution is noting but bring thread state running to Waiting or blocked or sleeping.using some method we can do it.
those methods are
1.Sleep();
2.yield();
3.join();
4.wait();
1.Sleep():
1.Runnable state where thread is ready for running waiting for thread scheduler to select.
2..Assume that Thread Scheduler Selects thread now thread in running State while running sleep method is called on current thread
3.After encounter sleep method call on current thread .it enter into sleep state
4.After thread finish his sleeping time again enter into Runnable State.
The sleep method is static method of class Thread.we use when we want to slow a thread down by forcing it to go sleep mode
when thread enter sleep state it will never back runnable state until sleep time over.
we need to pass time in milliseconds for sleep method.
sleep method throws Interrupted Exception when thread interrupted before it wake up time ,in which case it immediately
throw Interrupted Exception.
important point is when thread sleep time expires,doesn't mean it will running state ,When thread wake up it simply goes back to the runnable state
after thread scheduler selection only it will back to running state so there is no guarantee that the thread will start running again as soon as the time expires
and the thread wakes.
you cant put particular thread as sleep why because sleep is static method so you can put current thread only sleep mode.
Example:
In below example i created two threads first thread and second thread and default main thread also threre
so total three thread are there threads accessing static variable count if which thread got first chance to increment it get first position.
(nothing but which thread is first completed it get first rank)
package com.multi;
public class ThreadSleep {
static int count=0;
public static void main(String[] args) {
FirstThread firstThread= new FirstThread();
firstThread.start();
firstThread.setName("First");
SecondThread secondThread= new SecondThread();
secondThread.start();
secondThread.setName("Second");
System.out.println(Thread.currentThread().getName()+" :::IM not sleeping my rank is-->"+ ++count);
}
}
class FirstThread extends Thread {
@Override
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" :::IM sleeping my rank is-->"+ ++ThreadSleep.count);
}
}
class SecondThread extends Thread {
public void run() {
System.out.println(Thread.currentThread().getName()+" :::IM not sleeping my rank is-->"+ ++ThreadSleep.count);
}
}
Main :::IM not sleeping my rank is-->1
Second :::IM not sleeping my rank is-->2
First :::IM sleeping my rank is -->3
Output:
only First thread is sleeping that's why it gets last rank :).
you may get doubt second thread is not sleeping why it get second rankinstead of first. why because both main thread and first thread not sleeping.so its thread scheduler choice to pick up thread some time you may get second thread first rank.
thread scheduler may pickup first thread also first time when it pick up first firstthread that particular thread enter into sleep state .once it encounters sleep state it will not come out until its sleep time exceeds
mean while main thread and second thread execution will be over that's whyFirst thread always get last position.
Yield:
1.Runnable state where thread is ready for running waiting for thread scheduler to select.
2..Assume that Thread Scheduler Selects thread now thread in running State after that yield() method is called on current thread
3.After encounter Yield method call on current thread. if any other thread is available in Runnable
state (thread pool)it go back to Runnable state giving chance to run another Thread .
Before going to yield method we must aware thread priorities.
Thread always run with some priority by default thread priority 5 you can change thread priority calling
setPriority(10); method on thread instance .we can set thread priority between 1 to 10 range
Thread scheduler mostly chooses high priority thread from runnable to running state .
If thread enters into runnable state ,it has higer priority than other threads.
In most cases,there running thread will be equal or greater priority than the highest priority threads in pool.
Most important is don't rely on the thread priorities when writing multithread program why because
priority behavior not guaranteed.it's depend upon jvm implementation.
The purpose of yield static method is make the currently running thread back to runnable to allow other threads to run which having same priority.
when ever call yield() method on current thread never goes to wait/sleep/block state .mostly it goes to runnable state when any other thread in pool having same priority other wise i will not go runnable state also
because no other thread priority in pool not equal to current thread priority.
Example:
package com.multi;
public class YieldExample {
public static void main(String[] args) {
Thread2 thread2=new Thread2();
thread2.setName("thread2");
thread2.start();
Thread1 thread1=new Thread1();
thread1.setName("thread1");
thread1.start();
}
}
class Thread1 extends Thread{
@Override
public void run(){
System.out.println("Thread Name:::::"+Thread1.currentThread().getName());
System.out.println("Im---" +Thread1.currentThread().getName()+" not giving chance to any other thread to run my work is done");
}
}
class Thread2 extends Thread{
@Override
public void run(){
System.out.println("Thread Name:::::"+Thread1.currentThread().getName());
System.out.println(Thread1.currentThread().getName()+":::Im giving to chance another thread to run going back to runnable state");
Thread.yield();
System.out.println("Yes I am Back Again to running State");
}
}
Output:
Thread Name:::::thread1 Im---thread1 not giving chance to any other thread to run my work is done Thread Name:::::thread2 thread2:::Im giving to chance another thread to run going back to runnable state Yes I am Back Again to running StateThis output is not guaranteed it will change based on jvm implementation.
Join:
1.Runnable state where thread is ready for running waiting for thread scheduler to select.
2.Assume that Thread Scheduler Selects thread now thread in running State assume that join method is called on current thread
3.After encounter join method call on current thread .it enter into wait stateuntil target thread execution finish
4.After target thread execution over waiting thread again enter into Runnable State.
It's a non static method of a class thread.its required when one thread need to wait until another thread finish his work.
Consider one example like student marks calculation one thread is finding total marks of Student another
Thread is calculating average of the student .after completing total calculation thread only average thread
is need to calculate average so we need to combine average finding thread to total finding thread.
Example:
package com.multi;
public class StudentJoinExample {
static Student student=new Student();
public static void main(String[] args) {
/* setting student marks*/
student.setComputerMarks(60);
student.setMathsMarks(90);
student.setSocialMarks(80);
TotalCalculationThread totalCalculationThread=new TotalCalculationThread(); totalCalculationThread.start();
System.out.println("Calculating averege with in main thread it self"); try {
System.out.println("i am main thread need to wait untill total calculation done by another thread ");
totalCalculationThread.join();
}
catch (InterruptedException e)
{ e.printStackTrace();
}
System.out.println("total is done by another therad. main therad is now running");
int total=StudentJoinExample.student.getTotal();
float average=(total/3); System.out.println("average mark done by main thread:::::"+average); } }
class TotalCalculationThread extends Thread {
@Override public void run() {
System.out.println("Im in total calculation thread"); int total=StudentJoinExample.student.getComputerMarks()+ StudentJoinExample.student.getSocialMarks()+
StudentJoinExample.student.getMathsMarks();
System.out.println("total marks is::calculation done::"+total); StudentJoinExample.student.setTotal(total);
}
}
class Student{
int mathsMarks; int computerMarks;
int socialMarks; float average;
int total;
public int getMathsMarks()
{ return mathsMarks;
}
public void setMathsMarks(int mathsMarks)
{ this.mathsMarks = mathsMarks;
}
public int getComputerMarks() {
return computerMarks;
} public void setComputerMarks(int computerMarks) {
this.computerMarks = computerMarks;
}
public int getSocialMarks() {
return socialMarks;
}
public void setSocialMarks(int socialMarks)
{
this.socialMarks = socialMarks;
}
public float getAverage() {
return average;
} public void setAverage(float average)
this.average = average;
} public int getTotal() {
return total;
} public void setTotal(int total) {
this.total = total; }
}
Output:
Calculating averege with in main thread it self
i am main thread need to wait untill total calculation done by another thread
Im in total calculation thread
total marks is::calculation done::230
total is done by another therad. main therad is now running
average mark done by main thread:::::76.0
In above example one thread i created TotalCalculationThread in this thread i'm calculating total
0 comments: