前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JAVA|理解thread.join

JAVA|理解thread.join

作者头像
heidsoft
发布2020-07-16 11:01:09
4100
发布2020-07-16 11:01:09
举报
文章被收录于专栏:云计算与大数据

java.lang.Thread class provides the join() method which allows one thread to wait until another thread completes its execution. If t is a Thread object whose thread is currently executing, then t.join() will make sure that t is terminated before the next instruction is executed by the program. If there are multiple threads calling the join() methods that means overloading on join allows 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. There are three overloaded join functions.

  1. join(): It will put the current thread on wait until the thread on which it is called is dead. If thread is interrupted then it will throw InterruptedException. Syntax: public final void join()
  2. join(long millis) :It will put the current thread on wait until the thread on which it is called is dead or wait for specified time (milliseconds). Syntax: public final synchronized void join(long millis)
  3. join(long millis, int nanos): It will put the current thread on wait until the thread on which it is called is dead or wait for specified time (milliseconds + nanos). Syntax: public final synchronized void join(long millis, int nanos)

场景:多线程访问同一个变量叠加

代码语言:javascript
复制
package top.cloudmesh.join;

/**
 * thread join 方法测试
 */
public class JoinDemo {
    public static volatile int count = 0;

    //多线程访问控制
    public static synchronized void inccount(){
        count++;
        System.out.println(Thread.currentThread().getName());
    }
    public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=0; i<10000; i++){
                    inccount();
                }
            }
        },"t1");

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=0; i<10000; i++){
                    inccount();
                }
            }
        },"t2");

        t1.start();
        t2.start();
        try {
            t1.join();
            System.out.println("main: "+Thread.currentThread().getState());
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("value: "+count);
    }
}
代码语言:javascript
复制
What does this thread join code mean?

To quote from the Thread.join() method javadocs:

join() Waits for this thread to die.

There is a thread that is running your example code which is probably the main thread.

The main thread creates and starts the t1 and t2 threads. The two threads start running in parallel.
The main thread calls t1.join() to wait for the t1 thread to finish.
The t1 thread completes and the t1.join() method returns in the main thread. Note that t1 could already have finished before the join() call is made in which case the join() call will return immediately.
The main thread calls t2.join() to wait for the t2 thread to finish.
The t2 thread completes (or it might have completed before the t1 thread did) and the t2.join() method returns in the main thread.
It is important to understand that the t1 and t2 threads have been running in parallel but the main thread that started them needs to wait for them to finish before it can continue. That's a common pattern. Also, t1 and/or t2 could have finished before the main thread calls join() on them. If so then join() will not wait but will return immediately.

t1.join() means cause t2 to stop until t1 terminates?

No. The main thread that is calling t1.join() will stop running and wait for the t1 thread to finish. The t2 thread is running in parallel and is not affected by t1 or the t1.join() call at all.

In terms of the try/catch, the join() throws InterruptedException meaning that the main thread that is calling join() may itself be interrupted by another thread.

while (true) {
Having the joins in a while loop is a strange pattern. Typically you would do the first join and then the second join handling the InterruptedException appropriately in each case. No need to put them in a loop.



Main thread-->----->----->----->--block##########continue--->---->
                 \                 |               |
sub thread start()\                | join()        |
                   \               |               |
                    ---sub thread----->--->--->--finish
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-07-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 云数智圈 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档