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条)

报告相同问题?

悬赏问题

  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗