public class ThreadJoin {
public static void main(String[] args) {
// Create tasks
Runnable MyTaskB = new Task2();
// Create threads
Thread thread0 = new Thread(MyTaskB);
thread0.start();
}
}
//The task for printing a character a specified number of times
class Task1 implements Runnable {
int i = 0;
int j = 0;
public void run() {
Thread t = Thread.currentThread();
String name = t.getName();
i += 1;
j += 1;
System.out.println("[" + name + "] " + "i: " + i + " j: " + j);
}
}
//The task class for printing numbers from 1 to n for a given n
class Task2 implements Runnable {
@Override /** Tell the tread how to run */
public void run() {
Thread thread1 = new Thread(new Task1());
Thread thread2 = new Thread(new Task1());
Thread thread3 = new Thread(new Task1());
thread1.start();
thread2.start();
thread3.start();
try {
thread1.join();
// System.out.print("Num: " + 1 + " ");
thread2.join();
// System.out.print("Num: " + 2 + " ");
thread3.join();
// System.out.print("Num: " + 3 + " ");
System.out.print("Num: " + 1 + " ");
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}