在子线程完成执行之前主线程将退出吗?
我读了2篇文章
http://www.cs.mtu.edu/~shene/NSF-3/e-Book/FUNDAMENTALS/thread-management.html
在上面的文章中,在"线程终止"段中,它在Red中声明"如果父线程终止,它的所有子线程也会终止".
http://www.roseindia.net/java/thread/overview-of-thread.shtml
在上面的文章中,该页面的最后一行指出"main()方法执行可以完成,但程序将继续运行,直到所有线程完成其执行."
我付费他们是矛盾的.如果我错了,请专家指正.
在我的程序中,使用Main方法的程序调用2个线程的构造函数.在各个线程的构造函数中,我有start()方法.
TestA A = new TestA("TestA");
TestB B = new TestB("TestB");
public TestA(String name) {
System.out.println(name);
t = new Thread(this);
t.start();
}
Run Code Online (Sandbox Code Playgroud)
我想知道会发生什么,主线程在子线程完成执行之前终止?如果是这样,孩子仍然会线程,继续执行?
我尝试运行该程序,有时候即使主线程退出,所有子线程也会完成执行.在2个线程中,我正在处理一些文件.在testA线程A中,单独的1个文件有时没有得到处理.但很多时候,所有的文件都得到处理,我没有任何问题.
我在Java中了解到:子线程不会比主线程更活跃,但是,看起来,这个应用程序的行为显示出不同的结果.
子线程继续工作,而主线程已完成工作!
这是我做的:
public class Main {
public static void main(String[] args) {
Thread t = Thread.currentThread();
// Starting a new child thread here
new NewThread();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("\n This is the last thing in the main Thread!");
}
}
class NewThread implements Runnable {
private Thread t;
NewThread(){
t= new Thread(this,"My New Thread");
t.start();
}
public void run(){
for (int i = 0; i <40; i++) {
try {
Thread.sleep(4000);
System.out.printf("Second …Run Code Online (Sandbox Code Playgroud)