I've read the Thread
documentation and looked over a number of examples, but I'm not able to get my code to function properly. I want to guarantee that Thread
s are executed in the order t2, t3, t1, and am trying to use the join()
method to do so.
From what I understand, join()
will ensure that the instance of the Thread it is called on will run until killed before proceeding with the next Thread
's execution. Here's my code:
public class ThreadyKrueger extends Thread {
private Thread t;
private String threadName;
public ThreadyKrueger(String name) {
this.threadName = name;
System.out.println("Creating thead, \"" + this.threadName + "\"");
}
@Override
public void run() {
try {
System.out.println("Job being run by " + this.threadName);
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println("Thread " + this.threadName + " interrupted!");
}
System.out.println(this.threadName + " exiting...");
}
@Override
public void start() {
System.out.println("Starting " + this.threadName);
if (t == null) {
t = new Thread(this, this.threadName);
}
t.start();
}
}
public class ThreadMain {
public static void main(String[] args) throws InterruptedException {
//ensure order is t2, t3, t1
ThreadyKrueger t2 = new ThreadyKrueger("T2");
ThreadyKrueger t3 = new ThreadyKrueger("T3");
ThreadyKrueger t1 = new ThreadyKrueger("T1");
t2.start();
t2.join();
t3.start();
t3.join();
t1.start();
}
And the output I'm getting varies each time, but for instance:
Creating thead, "T2"
Creating thead, "T3"
Creating thead, "T1"
Starting T2
Starting T3
Starting T1
Job being run by T2
Job being run by T3
Job being run by T1
T1 exiting...
T2 exiting...
T3 exiting...
Clearly T2 is not killed before T3 starts, and so on. What am I missing (besides a few indents and brackets that were lost in copy/paste). Thank you.