问题: 父子线程的关系
今天突然有感而发, 想要来探讨一下主线程和子线程之间的关系。
例一:子线程执行时间较父线程慢
public class ThreadTest {public static void main(String[] args) {// 测试主线程 和 子线程Thread sonThread = new Thread(() -> {try {Thread.sleep(3000);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println("子线程结束");});sonThread.start();System.out.println("父线程结束");}
}
结果是都进行了执行,这说明主线程执行完毕后,会等待子线程进行执行完毕后退出。
例二:主线程执行的较慢
public class ThreadTest {public static void main(String[] args) {// 测试主线程 和 子线程Thread sonThread = new Thread(() -> {System.out.println("子线程结束");});sonThread.start();try {Thread.sleep(3000);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println("父线程结束");}
}
结果也是都进行了执行
而对于Go来说则不一样,Go一旦主线程结束,协程就会自动的退出
例三 主线程执行的较快
func main() {go func() {fmt.Println("1111")}()fmt.Println("主线程结束")
}
如果想要协程执行完才退出的话,必须使用阻塞来进行控制。