Monday, December 14, 2009

Thread: Join API

Thread: Join API

In multithreaded environment, T2 thread may need the result from T1 thread. Hence, T2 needs to check the thread state of T1 until the T1 state turn to TERMINATED in specified polling interval using sleep API.





while(Thread.State.TERMINATED != t1.getState())
{
Thread.sleep(1000);//wait for 1 second
}



This loop takes considerable CPU time. Instead of we do this thread monitoring job in our code base to wait for the particular thread's completion. We can utilize the Thread API join(), which minimize the CPU cycle usage and avails as similar functionality.



threadObj.join() API makes current Thread to wait for threadObj to complete.


public class JoinTest {
public static void main(String[] args) {
final Thread t1= new Thread()
{
@Override
public void run() {
for(int i=0;i<1000;i++)
{
System.out.println(i);
}
}
};

Thread t2= new Thread()
{
@Override
public void run() {

// Using sleep and state check in our code
// while(Thread.State.TERMINATED != t1.getState())
// {
// try{Thread.sleep(1000);//wait for 1 second
//
// }catch(Exception e)
// {
// e.printStackTrace();
// }
// }

//Using join API
try{t1.join();}catch(Exception e)
{
e.printStackTrace();
}

System.out.println("Hello From T2, after T1 terminated");
}
};

t2.start();
t1.start();


}
}

No comments:

Post a Comment

Recent Posts

Unix Commands | List all My Posts

Texts

This blog intended to share the knowledge and contribute to JAVA Community such a way that by providing samples and pointing right documents/webpages. We try to give our knowledege level best and no guarantee can be claimed on truth. Copyright and Terms of Policy refer blogspot.com