StackTc
StackTc
2018-01-12 17:40

线程跟main线程的关系

5
  • 线程
  • java

代码跟运行结果如下,本人只想知道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

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

6条回答

为你推荐

换一换