Understanding join()

故事扮演 提交于 2019-12-21 05:27:06

问题


Suppose a thread A is running. I have another thread, B, who's not. B has been started, is on runnable state.

What happens if I call: B.join()?

Will it suspend the execution of A or will it wait for A's run() method to complete?


回答1:


join() will make the currently executing thread to wait for the the thread it is called on to die.

So - If A is running, and you call B.join(), A will stop executing until B ends/dies.




回答2:


Join waits till the thread is dead. If you call it on a dead thread, it should return immediately. Here's a demo:

public class Foo extends Thread {

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println("Start");

        Foo foo = new Foo();
        try {
            // uncomment the following line to start the foo thread.
            // foo.start();
            foo.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Finish");
    }

    public void run() {
        System.out.println("Foo.run()");
    }

}



回答3:


From http://java.sun.com/docs/books/tutorial/essential/concurrency/join.html

The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing,

t.join();

causes the current thread to pause execution until t's thread terminates. Overloads of join allow the programmer to specify a waiting period. However, as with sleep, join is dependent on the OS for timing, so you should not assume that join will wait exactly as long as you specify.

I can strongly recommend the Java Tutorial as a learning resource.




回答4:


Calling the join method on a thread causes the calling thread to wait for the thread join() was called on to finish. It does not affect any other threads that are not the caller or callee.

In your example, A would only wait for B to complete if you are calling B.join() from A. If C is calling B.join(), A's execution is unaffected.




回答5:


I think that if A is the current thread running. A call to B.join() will suspend it until B's run() method completes. Is this correct?




回答6:


Whichever thread you call B.join() from will block and wait for B to finish.



来源:https://stackoverflow.com/questions/1897524/understanding-join

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!