线程跟main线程的关系

代码跟运行结果如下,本人只想知道main中的isAlive在t线程启动前为什么是死的,
在t线程启动后为什么是活的。两者有什么必然的联系呢。

 public class CountOperate extends Thread {

    public CountOperate() {
        System.out.println("CountOperate start");
        System.out.println("Thread.currentThread().getName = " + Thread.currentThread().getName());
        System.out.println("Thread.currentThread().isAlive = " + Thread.currentThread().isAlive());
        System.out.println("this.getName = " + this.getName());
        System.out.println("this.isAlive = " + this.isAlive());
        System.out.println("CountOperate end");
    }

    public void run() {
        System.out.println("run start");
        System.out.println("Thread.currentThread().getName = " + Thread.currentThread().getName());
        System.out.println("Thread.currentThread().isAlive = " + Thread.currentThread().isAlive());
        System.out.println("this.getName = " + this.getName());
        System.out.println("this.isAlive = " + this.isAlive());
        System.out.println("run end");
    }

}

 public class ThreadTest {
    private static final long count = 10000001;
    public static void main(String[] args) throws InterruptedException {
        CountOperate c = new CountOperate();
        Thread t = new Thread(c);
        System.out.println("main begin t isAlive = " + t.isAlive());
        t.setName("A");
        t.start();
        System.out.println("main end t isAlive = " + t.isAlive());
    }
}

运行结果

CountOperate start
Thread.currentThread().getName = main
Thread.currentThread().isAlive = true
this.getName = Thread-0
this.isAlive = false
CountOperate end
main begin t isAlive = false
run start
main end t isAlive = true
Thread.currentThread().getName = A
Thread.currentThread().isAlive = true
this.getName = Thread-0
this.isAlive = false
run end

你这里两次调用t.isAlive全都是线程t的死亡状态,跟main线程没有半点关系;如果要获取main线程的状态,只需在t启动前,调用Thread.currentThread().isAlive(),
而且线程之间的状态都是互相独立的,没有你说的什么必然联系

图片说明
看这个图片,新建和死亡以外,就是活的。

当程序使用new创建一个线程后,在调用start以前就是新建状态(isalive=false)
一旦调用start就是活的了。
线程调用stop()方法时或run()方法执行结束后,即处于死亡状态。

你的代码没有写两者啊,你调用的就是t.isAlive()啊,那t线程当然要start后才isAlive=true,因为start时启动线程。

图片说明

你在这里调用的就是t.isAlive();所以在t.start之前都是false,在t.start之后就是true了,如果你想测验主线程的话,应该调用的是Thread.currentThread().isAlive();

你调用的就是t.isAlive()啊,那t线程当然要start后才isAlive=true,因为start时启动线程。