Table of Content 7
- Lecture1.1
- Lecture1.2
- Lecture1.3
- Lecture1.4
- Lecture1.5
- Lecture1.6
- Quiz1.1
Thread Joining
- This allows to wait one thread until the task of other thread is completed.
- join() is a method used for thread joining.
- In main thread -> t1.join()
Main thread will be joined at the end of t1.
- In t1 thread -> t2.join
T1 thread will be joined at the end of t2.
import java.io.*;
class ThreadJoin extends Thread{
public void run(){
for (int i = 0; i< 2; i++){
try{
Thread.sleep(500);
System.out.println(“Thread: “+ Thread.currentThread().getName());
}
catch(Exception ex)
{
System.out.println(“Exception caught”);
}
System.out.println(i);
}
}
}
class Intellipaat{
public static void main (String[] args)
{
ThreadJoining t1 = new ThreadJoining();
ThreadJoining t2 = new ThreadJoining();t1.start();
try{
System.out.println(“Thread: ”+ Thread.currentThread().getName());
t1.join();
}
catch(Exception ex)
{
System.out.println(“Exceptioncaught”);
}t2.start();
try
{
System.out.println(“Thread: ”+ Thread.currentThread().getName());
t2.join();
}catch(Exception e){
System.out.println(“Exception caught”);}
}
}
class ThreadJoin extends Thread{
public void run(){
for (int i = 0; i< 2; i++){
try{
Thread.sleep(500);
System.out.println(“Thread: “+ Thread.currentThread().getName());
}
catch(Exception ex)
{
System.out.println(“Exception caught”);
}
System.out.println(i);
}
}
}
class Intellipaat{
public static void main (String[] args)
{
ThreadJoining t1 = new ThreadJoining();
ThreadJoining t2 = new ThreadJoining();t1.start();
try{
System.out.println(“Thread: ”+ Thread.currentThread().getName());
t1.join();
}
catch(Exception ex)
{
System.out.println(“Exceptioncaught”);
}t2.start();
try
{
System.out.println(“Thread: ”+ Thread.currentThread().getName());
t2.join();
}catch(Exception e){
System.out.println(“Exception caught”);}
}
}
Output:
Thread: main
Thread: Thread0
Thread: Thread0
1
Thread: main
Thread: Thread1
Thread: Thread1
1
Prev Thread Scheduler