From what I understand, a C process will be terminated when the main (parent) thread reaches the end of its execution or returns. This behavior can be altered by using the pthreadjoin function in the main thread.
However, a Java process will still keep running until all the threads finishes their execution even if the main thread has returned or finished. (This can be changed by making the child threads run as daemons in Java).
Why did Java choose to do it this way?
#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 Output
Thread created successfully
First thread processing
Thread created successfully
Second thread processing
Process Exit
Neither thread finishes it's task before process exits.
However, in Java:
Java Code Sample
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 Ouptut
Thread 1 starting.
Thread 2 starting.
Thread running.
Main thread finished.
Thread running.
Thread ending.
Thread ending.
Both threads complete their tasks even though the main thread has finished long ago. As can be seen, there are no daemon threads. Edit: From Java doc: The Java Virtual Machine continues to execute threads until all threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.
Unpublished comment
Viết câu trả lời