IsAlive () returns false

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?

+4
source share
2 answers

The first scenario:

Your current ("main") thread starts a new thread, then the call obj.wait(3000);causes the current thread to wait with a timeout of 3 seconds. This is not a new stream that is waiting!

, . "..." .

, "" ( 3 ), , isAlive() false.

:

( "" ) .

, System.out.println().

, , , , isAlive() true.

, , . isAlive() false, , (- > ).


P.S. - "" isAlive(), , , false. :

    System.out.println("Before creating tunnel...");
    final MyTunnel tunnel = new MyTunnel();
    System.out.println("After creating tunnel...");

    for (int i = 0; i < 100; ++i) {
        System.out.print("");
    }

    System.out.println("Is tunnel alive ? " + tunnel.isAlive()); // returns false on my machine
0

, . , , .

3 , .

, isAlive, .

wait , sleep. InterruptedExceptions .

0

Source: https://habr.com/ru/post/1673600/


All Articles