StackTc 于 2018.01.13 01:40 提问
- 线程跟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 endmain begin t isAlive = false
run startmain end t isAlive = true
Thread.currentThread().getName = A
Thread.currentThread().isAlive = true
this.getName = Thread-0
this.isAlive = false
run end
-
- weilusi1991 2018.01.23 10:47
- 已采纳
你这里两次调用t.isAlive全都是线程t的死亡状态,跟main线程没有半点关系;如果要获取main线程的状态,只需在t启动前,调用Thread.currentThread().isAlive(),
而且线程之间的状态都是互相独立的,没有你说的什么必然联系
-
-
caozhy
2018.01.13 02:43
-
- qq_41626844 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
- 3 个月之前 回复
-
- qq_38074369 2018.01.13 08:36
你的代码没有写两者啊,你调用的就是t.isAlive()啊,那t线程当然要start后才isAlive=true,因为start时启动线程。
-
- doujinlong1 2018.01.13 11:25
-
- qq_39591507 2018.01.14 10:54
你main函数只有启动了线程以后,isAlive()函数才会不断判断线程是否存活
-
- hhh1258 2018.01.15 09:14
你调用的就是t.isAlive()啊,那t线程当然要start后才isAlive=true,因为start时启动线程。