子线程阻止java中的父线程
public static void main(String[] args) throws Exception { new Thread(new Runnable() { public void run() { while(true) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Hello"); } } }).run(); System.out.println("Bye"); }
在主要的thead中,我创建了一个新的线程,它将每秒打印“你好”。 为什么最后的“再见”从未打印过? 换句话说,为什么子线程阻塞主线程?
因为您正在调用run()
而不是start()
。
你绝不能直接调用run()
。 如果你调用start()
,程序将在另一个线程中为你调用run()
。 (就像你想要的那样。)通过自己调用run()
,你将使用父线程进入run()
方法,并使用你的父线程卡在一个永恒的循环中。