C&;JAVA
据我所知,C进程将在主(父)线程返回或到达执行结束时立即终止。(这可以在主线程中使用pthread_join进行更改) 但是,即使主线程已经返回或完成,Java进程仍将保持运行,直到所有线程完成其执行。(这可以通过使子线程在Java中作为守护进程运行来改变) 为什么Java选择这样做 C代码示例: 在进程退出之前,两个线程都没有完成它的任务 但是,在Java中: Java代码示例 爪哇乌普图 两个线程都完成了它的任务,即使主线程已经完成了很长一段时间。可以看出,没有守护进程线程 编辑:来自:C&;JAVA,java,c,multithreading,pthreads,Java,C,Multithreading,Pthreads,据我所知,C进程将在主(父)线程返回或到达执行结束时立即终止。(这可以在主线程中使用pthread_join进行更改) 但是,即使主线程已经返回或完成,Java进程仍将保持运行,直到所有线程完成其执行。(这可以通过使子线程在Java中作为守护进程运行来改变) 为什么Java选择这样做 C代码示例: 在进程退出之前,两个线程都没有完成它的任务 但是,在Java中: Java代码示例 爪哇乌普图 两个线程都完成了它的任务,即使主线程已经完成了很长一段时间。可以看出,没有守护进程线程 编辑:来自: J
Java虚拟机将继续执行线程,直到所有非守护进程线程的线程都已死亡,方法是从调用run方法返回,或者抛出传播到run方法之外的异常。您的语句在几个方面不正确:
sleep(2);
printf("\nProcess Exit\n");
return 0;
}
致:
如果第一个线程从
main
返回,则进程将终止。C标准(第5.1.2.2.3节)规定,从main
返回等同于调用exit
,这就是终止过程的原因。然后线程终止,因为进程终止,而不是相反。我认为你错了。我添加了输出,以准确显示每种情况下发生的情况。我还从Java文档中添加了一个注释,其中指出所有线程都将继续执行,直到只剩下守护进程线程。至于C,我只是说主线程终止的时刻,而不是指操作系统必须执行的任何清理。现在这完全有道理了。谢谢你的精彩解释。
Thread created successfully
First thread processing
Thread created successfully
Second thread processing
Process Exit
public class ThreadTermination implements Runnable {
@Override
public void run() {
System.out.println("Thread running.");
try {
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread ending.");
}
public static void main(String[] args) {
ThreadTermination t1 = new ThreadTermination();
ThreadTermination t2 = new ThreadTermination();
Thread thr1 = new Thread(t1);
System.out.println("Thread 1 starting.");
thr1.start();
Thread thr2 = new Thread(t2);
System.out.println("Thread 2 starting.");
thr2.start();
System.out.println("Main thread finished.");
}
}
Thread 1 starting.
Thread 2 starting.
Thread running.
Main thread finished.
Thread running.
Thread ending.
Thread ending.
sleep(2);
printf("\nProcess Exit\n");
return 0;
}
sleep(2);
printf("\nThread Exit\n");
pthread_exit(0);
return 0; // will never execute
}