java主线程结束和子线程结束之间的关系

情况1:正常情况下,主线程启动了子线程,主线程、子线程各自执行,彼此不受影响。

当你在run一个Java application的时候,这个时候系统会开一个进程。然后这个进程启动了Main线程。Java进程确定虚拟机中没有线程运行的时候,退出进程。或者也可以用System.exit(0);强制退出进程


代码示例如下:参考Thinkingin java代码

[java] view plain copy
  1. class LiftOff implements Runnable {  
  2.   
  3.     Logger logger = LoggerFactory.getLogger(LiftOff.class);  
  4.   
  5.     protected int countDown = 10// Default  
  6.     private static int taskCount = 0;  
  7.     private final int id = taskCount++;  
  8.     public LiftOff() {}  
  9.     public LiftOff(int countDown) {  
  10.         this.countDown = countDown;  
  11.     }  
  12.     public String status() {  
  13.         return "#" + id + "(" +  
  14.                 (countDown > 0 ? countDown : "Liftoff!") + "), ";  
  15.     }  
  16.     @Override  
  17.     public void run() {  
  18.         while(countDown-- > 0) {  
  19.             logger.info(status());  
  20.             Thread.yield();  
  21.         }  
  22.     }  
  23. }  
  24.   
  25. public class MainThread{  
  26.   
  27.     Logger logger = LoggerFactory.getLogger(MainClass.class);  
  28.   
  29.     @Test  
  30.     public void test(){  
  31.         Thread t = new Thread(new LiftOff());  
  32.         t.start();  
  33.         logger.info("waiting for liftoff");  
  34.     }  
  35. }  

显示结果:


情况2:需求是主线程执行结束,由主线程启动的子线程都结束


代码如下

[java] view plain copy
  1. class SimpleDaemons implements Runnable {  
  2.     Logger logger = LoggerFactory.getLogger(SimpleDaemons.class);  
  3.     public void run() {  
  4.         try {  
  5.             while (true) {  
  6.                 TimeUnit.MILLISECONDS.sleep(100);  
  7.                 logger.info("run..");  
  8.             }  
  9.         } catch (InterruptedException e) {  
  10.             logger.info("sleep() interrupted");  
  11.         }  
  12.     }  
  13. }  
  14.   
  15. public class MainThread {  
  16.     Logger logger = LoggerFactory.getLogger(MainThread.class);  
  17.     @Test  
  18.     public void test() {  
  19.         for(int i = 0; i < 5; i++) {  
  20.             Thread daemon = new Thread(new SimpleDaemons());  
  21.             daemon.setDaemon(true); // Must call before start()  
  22.             daemon.start();  
  23.         }  
  24.         logger.info("All daemons started");  
  25.         try {  
  26.             TimeUnit.MILLISECONDS.sleep(175);  
  27.         } catch (InterruptedException e) {  
  28.             e.printStackTrace();  
  29.         }  
  30.     }  
  31. }  

运行结果:


情况3:需求是子线程执行结束,主线程等待启动的子线程都结束之后再结束


代码:

[java] view plain copy
  1. public class IsAliveTest {  
  2.     public static void main(String args[]) throws Exception {  
  3.   
  4.         Thread t = new Thread(new ThreadDemo());  
  5.         // this will call run() function  
  6.         t.start();  
  7.   
  8.         // waits for this thread to die  
  9.         t.join();  
  10.   
  11.         // tests if this thread is alive  
  12.         System.out.println("thread t status = " + t.isAlive());  
  13.         System.out.println("thread main status = " + Thread.currentThread().isAlive());  
  14.     }  
  15. }  
  16.   
  17. class ThreadDemo implements Runnable {  
  18.   
  19.     public void run() {  
  20.   
  21.         Thread t = Thread.currentThread();  
  22.         // tests if this thread is alive  
  23.         System.out.println("status = " + t.isAlive());  
  24.         try {  
  25.             t.sleep(3000L);  
  26.         } catch (InterruptedException e) {  
  27.             e.printStackTrace();  
  28.         }  
  29.     }  
  30. }  
测试结果


什么情况下一个java thread reach the ‘Die’ state?

 

From the ThreadAPI, here is a complete list:

  1. If the run() method returns. 例如join()之后

  2. If an exception is thrown that propagates beyond the run method.

  3. If it is a daemon thread and all non-daemonthreads have 'died' 非后台线程都结束

  4. If the exit method of class Runtime has been called (even at another thread).


实际上,我们对Thread类没有什么控制权,我们几乎不能设置线程的任何状态,我们只能创建任务,并通过某种方式使用线程驱动这个任务

所以,在编写多线程代码的时候,遵循规则就变得非常重要
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值