java中子线程阻塞父线程 [英] child thread blocks parent thread in java

查看:66
本文介绍了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");
}

在主标题中,我创建了一个新线程,它将每秒打印hello".为什么最后的再见"从未印刷过?换句话说,为什么子线程阻塞了主线程?

In the main thead, I create a new thread, which will print "hello" every second. Why the final "Bye" never got print? In the other word, why the child thread blocks the main thread?

推荐答案

因为你调用的是 run(),而不是 start().

Because you are calling run(), instead of start().

您绝对不能直接调用 run().如果您调用 start(),程序将在不同的线程中为您调用 run().(如您所愿.)通过自己调用 run(),您将进入带有父线程的 run() 方法,并陷入一个永恒的循环中,您的父线程.

You must never call run() directly. If you call start(), the program will call run() for you, in a different thread. (Like you wanted.) By calling run() yourself, you are going into the run() method with the parent thread, and get stuck in an eternal loop, with your parent thread.

这篇关于java中子线程阻塞父线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆