据我了解,一旦主(父)线程返回或执行结束,C 进程就会终止。 (这可以在主线程中使用 pthread_join 来改变)。
但是,即使主线程已经返回或结束,Java 进程仍将继续运行,直到所有线程执行完毕。 (这可以通过让子线程在 Java 中作为守护进程运行来改变)。
Java 为什么选择这样做?
C 代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
pthread_t tid[2];
void *doSomeThing(void *arg) {
unsigned long i = 0;
pthread_t id = pthread_self();
if (pthread_equal(id, tid[0])) {
printf("\n First thread processing\n");
}
else {
printf("\n Second thread processing\n");
}
for (i = 0; i < (0xFFFFFFFF); i++);
printf("\n Threads finished.\n");
return NULL;
}
int main() {
int i = 0;
int err;
while(i < 2)
{
err = pthread_create(&(tid[i]), NULL, &doSomeThing, NULL);
if (err != 0)
printf("\ncan't create thread :[%s]", strerror(err));
else
printf("\n Thread created successfully\n");
i++;
}
sleep(2);
printf("\nProcess Exit\n");
return 0;
}
C输出
Thread created successfully
First thread processing
Thread created successfully
Second thread processing
Process Exit
在进程退出之前,两个线程都没有完成它的任务。
但是,在 Java 中:
Java 代码示例
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.");
}
}
Java 输出
Thread 1 starting.
Thread 2 starting.
Thread running.
Main thread finished.
Thread running.
Thread ending.
Thread ending.
两个线程都完成了它的任务,即使主线程早就完成了。可以看出,没有守护线程。
编辑:来自 Java doc :
Java 虚拟机继续执行线程,直到所有不是守护线程的线程都死掉,方法是从对 run 方法的调用返回,或者抛出一个传播到 run 方法之外的异常
最佳答案
From my understanding, a C process will be terminated as soon as the main (parent) thread returns or reaches the end of execution.
没有。 C 进程不会仅仅因为第一个线程执行结束而终止。为了证明这一点,将您的代码从:
sleep(2);
printf("\nProcess Exit\n");
return 0;
}
收件人:
sleep(2);
printf("\nThread Exit\n");
pthread_exit(0);
return 0; // will never execute
}
如果第一个线程从 main
返回,进程将终止。 C 标准(第 5.1.2.2.3 节)说从 main
返回等同于调用 exit
,这就是终止进程的原因。然后线程终止,因为进程终止,而不是相反。
关于java - C和Java之间的线程终止区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34487321/