开发者

Understanding join()

开发者 https://www.devze.com 2022-12-14 09:39 出处:网络
Suppose a thread A is running. I have another thread, B, who\'s not. 开发者_如何学JAVAB has been started, is on runnable state.

Suppose a thread A is running. I have another thread, B, who's not. 开发者_如何学JAVAB 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?


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.


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()");
    }

}


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.


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.


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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号