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类没有什么控制权,我们几乎不能设置线程的任何状态,我们只能创建任务,并通过某种方式使用线程驱动这个任务

所以,在编写多线程代码的时候,遵循规则就变得非常重要

### Java 主线程子线程中的异常处理行为 在Java编程环境中,当主线程(main thread)或任何子线程(child threads)抛出未捕获的异常时,默认情况下JVM会打印堆栈跟踪(stack trace),随后对于主线程可能会终止程序执行;而对于子线程,则通常仅该特定线程结束而不会影响到整个应用程序继续运行[^1]。 为了更好地管理这些情况,在设计阶段就应该考虑如何优雅地处理可能出现的各种错误条件。一种常见做法是在启动新线程的地方设置`Thread.UncaughtExceptionHandler`来监听并响应那些未能被内部逻辑捕捉下来的异常事件: ```java public class ThreadExceptionExample { public static void main(String[] args) { // 创建一个新的线程实例 Thread t = new Thread(() -> { throw new RuntimeException("Uncaught exception in thread"); }); // 设置未捕获异常处理器 t.setUncaughtExceptionHandler((thread, throwable) -> System.out.println( "Caught Exception from " + thread.getName() + ": " + throwable.getMessage())); // 启动线程 t.start(); try { t.join(); // 等待t线程完成 } catch (InterruptedException e) { Thread.currentThread().interrupt(); // 恢复中断状态 } } } ``` 此外,如果希望自定义异常类以便更精确地区分不同类型的失败情形,并允许调用者针对具体问题采取适当措施的话,可以遵循建议创建专门用于描述特殊情况下的异常类型[^2]。 通过这种方式不仅可以提高代码可读性维护性,同时也使得调试过程变得更加简单明了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值