Thread Join method in java
SAMPLE PROGRAM
Note: output might differ from system to system in threading
public class MainClass {
public static void main(String[] args) throws InterruptedException
{
Test
testObj=new Test();
Thread
t1=new Thread(testObj);
t1.start(); //main thread
created the t1 thread
for(int i=0;i<20;i++){
System.out.println("MAIN thread
with i = "+i);
}
t1.join();
System.out.println("End of main
thread");
}
}
class Test implements Runnable{
@Override
public void run() {
for(int i=0;i<20;i++){
System.out.println("thread with i
= "+i);
}
}
}
Output:
MAIN thread with i = 0
thread with i = 0
MAIN thread with i = 1
thread with i = 1
MAIN thread with i = 2
thread with i = 2
MAIN thread with i = 3
thread with i = 3
MAIN thread with i = 4
thread with i = 4
MAIN thread with i = 5
thread with i = 5
MAIN thread with i = 6
thread with i = 6
MAIN thread with i = 7
thread with i = 7
MAIN thread with i = 8
thread with i = 8
MAIN thread with i = 9
thread with i = 9
MAIN thread with i = 10 //till here both main and t1 thread executing parallely
thread with i = 10 //join method called by main and main halts for sometime
thread with i = 11
thread with i = 12
thread with i = 13
thread with i = 14
thread with i = 15
thread with i = 16
thread with i = 17
thread with i = 18
thread with i = 19
MAIN thread with i = 11 //t1 finishes execution and main continues executing
MAIN thread with i = 12
MAIN thread with i = 13
MAIN thread with i = 14
MAIN thread with i = 15
MAIN thread with i = 16
MAIN thread with i = 17
MAIN thread with i = 18
MAIN thread with i = 19
End of main thread
Comments
Post a Comment