StackTc 2018-01-12 17:40 采纳率: 90.9%
浏览 2186
已采纳

线程跟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

  • 写回答

5条回答

  • weilusi1991 2018-01-23 02:47
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站