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 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图