I have a class MyTunnelthat extends the class Thread:
public class MyTunnel extends Thread {
protected Object obj;
public MyTunnel() {
super(MyTunnel.class.getName());
obj = new Object();
prepare();
}
public void prepare() {
System.out.println("Before starting...");
start();
synchronized(obj) {
try {
obj.wait(3000);
} catch (InterruptedException e) {
System.out.println("Error while waiting thread to start");
}
}
System.out.println("After starting...");
}
@Override
public void run() {
System.out.println("running...");
}
}
When I run the following code in the main thread:
System.out.println("Before creating tunnel...");
MyTunnel tunnel = new MyTunnel();
System.out.println("After creating tunnel...");
System.out.println("Is tunnel alive ? " + tunnel.isAlive());
I see the listing as follows:
Before creating tunnel...
Before starting...
running...
After starting...
After creating tunnel...
Is tunnel alive ? false
My question is why it tunnel.isAlive()returns false (in the last printed message)?
But if I change the function prepare()to:
public void prepare() {
System.out.println("Before starting...");
start();
System.out.println("After starting...");
}
run the code again, tunnel.isAlive()then return true. Why?
source
share