【问题标题】:what happens if thread calls join() on itself如果线程自己调用 join() 会发生什么
【发布时间】:2016-06-24 13:00:14
【问题描述】:

从我在这里读到的Thread join on itself ;

当join方法被自己调用时,它应该永远等待

我目前正在准备 ocajp 8 认证,为此经历了转储,当我得到这个问题时,我认为主要的应该永远等待

     public class startinginconstructor extends Thread
    {
        private int x=2;
        startinginconstructor()
        {   
            start();
        }
        public static void main(String[] args) throws Exception
        {
        new startinginconstructor().makeitso(); 
        }
        public void makeitso() throws Exception
        {
            x=x-1;
            System.out.println(Thread.currentThread().getName()+" about to call join ");
            join();
            System.out.println(Thread.currentThread().getName()+" makeitso completed "); 

           //  above line shouldn't be executed (method shouldn't be completed as well )since it joined on itself..?

        }
        public void run()
        {
    System.out.println(Thread.currentThread().getName()+" run started ");
        x*=2;
    System.out.println(Thread.currentThread().getName()+" run about to complete ");  
        }
    }

程序以以下输出结束

main about to call join
Thread-0 run started
Thread-0 run about to complete
main makeitso completed

我是否错误地理解了线程永远等待的含义,或者我错过了什么

注意:我知道从构造函数开始线程不是推荐的做法。这是转储中的确切问题,所以我只是粘贴了它(* 实际上不是很准确,我已经放置了 println 语句来查看程序的流程)

【问题讨论】:

    标签: java multithreading wait


    【解决方案1】:

    在您的示例中没有加入自身的线程。

    您示例中的 main() 线程创建了一个新线程,然后它加入了新线程。

    不要将 Thread(即 java 对象)与 thread(代码的执行)混淆。所有方法都属于同一个 Thread 对象,但它们运行在两个不同的线程中。

    【讨论】:

      【解决方案2】:

      James 是正确的(我 +1),我只是想让这一点更明确。这是发生了什么:

      您的主线程构造了startinginconstructor 构造函数。

      构造函数调用start,这将导致startinginconstructor对象在新线程中有它的run方法。

      之后主线程将继续调用makeitso。在makeitso中this是startinginconstructor对象,所以结果是主线程一直等到startinginconstructor对象代表的线程完成。

      Java 对象可以被任何线程调用,仅仅因为对象扩展了 Thread 并不意味着该线程上正在发生对该方法的任何调用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-03
        • 1970-01-01
        • 1970-01-01
        • 2012-05-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-06
        相关资源
        最近更新 更多