Java thread is essentially a final method which cannot be overridden. If there are two threads t1 and t2, when t2.join() is executed from thread t1, then thread t1 waits for t2 to complete execution before attempting to proceed it's own execution. If a sleeping thread is interrupted by a join() method, then an interruptedexception is thrown.
One of the main use cases of join - while implementing cache, have the initializing thread execute before having other code execution. Serializing 2 functions.
With Java 5, there are two techniques - CyclicBarrier and CountDownLatch to implement thread scenarios of executing one thread after another.
Another cool feature of Java5, that helps use of TimeUnit -
TimeUnit.SECONDS.sleep(2); makes the existing thread wait for 2 minutes and then complete execution.
public class ThreadJoinExample{
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Thread running " + Thread.currentThread());
Thread t1 = new Thread() {
public void run() {
try {
System.out.println("Thread running " + Thread.currentThread());
TimeUnit.SECONDS.sleep(2);
System.out.println("Thread running " + Thread.currentThread());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread finished " + Thread.currentThread());
}
}
One of the main use cases of join - while implementing cache, have the initializing thread execute before having other code execution. Serializing 2 functions.
With Java 5, there are two techniques - CyclicBarrier and CountDownLatch to implement thread scenarios of executing one thread after another.
Another cool feature of Java5, that helps use of TimeUnit -
TimeUnit.SECONDS.sleep(2); makes the existing thread wait for 2 minutes and then complete execution.
public class ThreadJoinExample{
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Thread running " + Thread.currentThread());
Thread t1 = new Thread() {
public void run() {
try {
System.out.println("Thread running " + Thread.currentThread());
TimeUnit.SECONDS.sleep(2);
System.out.println("Thread running " + Thread.currentThread());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread finished " + Thread.currentThread());
}
}
No comments:
Post a Comment