w25632 2008-06-24 11:37
浏览 120
已采纳

多线程问题

java中如果主线程关闭(main),那么创建的其它子线程还能运行不?我的例子:
public class t {
public static void main(String[] args) {

    System.out.println("kaishi");
    asd th = new asd();
    th.start();
    System.out.println(System.currentTimeMillis());
    System.out.println("tuichu");
    System.out.println(Thread.currentThread().getName()+System.currentTimeMillis());
    System.exit(0);
}

}

class asd extends Thread {

public void run() {
    while (true) {
        System.out.println(Thread.currentThread().getName()+System.currentTimeMillis());
    }
}

}
结果是kaishi
1214278000531
tuichu
main1214278000531
Thread-01214278000531
Thread-01214278000531
Thread-01214278000531
Thread-01214278000531
Thread-01214278000531
Thread-01214278000531
Thread-01214278000531
Thread-01214278000531
Thread-01214278000531
Thread-01214278000531
Thread-01214278000531
Thread-01214278000531
Thread-01214278000531
Thread-01214278000531
Thread-01214278000531
Thread-01214278000531
Thread-01214278000531
Thread-01214278000531
Thread-01214278000531
Thread-01214278000531
Thread-01214278000531这个能说明主线程关闭后子线程也关闭吗?
[b]问题补充:[/b]
那主线程(main)关闭是不是进程关闭呢?
[b]问题补充:[/b]
既然System.exit(0); 是退出jvm,那怎么退出后还会运行一段时间的新建线程呢?

  • 写回答

5条回答 默认 最新

  • hjgundam 2008-06-24 12:22
    关注

    如果你不加System.exit(0); 这样main会在运行结束后,调用Thread类的private方法Thread.exit()将其自身在ThreadGroup中remove掉,但是其产生的非守护线程任然会继续运行.

    但如果这样
    [code="java"]
    public class t {
    public static void main(String[] args) {

    System.out.println("kaishi");
    asd th = new asd();
    th.setDaemon(true);
    th.start();
    System.out.println(System.currentTimeMillis());
    System.out.println("tuichu");
    System.out.println(Thread.currentThread().getName()+System.currentTimeMillis());
    //System.exit(0);
    }

    }

    class asd extends Thread {

    public void run() {
    while (true) {
    System.out.println(Thread.currentThread().getName()+System.currentTimeMillis());
    }
    }
    }
    [/code]
    即使不加System.exit(0),在主线程结束后,其守护线程也会随之中止。

    System.exit(int)的javadoc是这样描述的:
    Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.
    是用来中止虚拟机,所以该程序的所有线程将都会中止

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题