Understanding join()

坚强是说给别人听的谎言 提交于 2019-12-03 17:23:39
brabster

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.

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