Mark Knowledge of Java Thread (1): Join Method

Join is A Simple Way

Assuming a scenario of mulit-threads, there are two threads(tA and tB). How can we insure that tB must be finished before tA is finished? A simple way is to let tB joint tA so Thread.join() is convenience.

Join Talk to You

There are three join methods which are defined in thread class.

- public final void join() throws InterruptedException
- public final synchronized void join(long millis) throws InterruptedException
- public final synchronized void join(long millis, int nanos) throws InterruptedException

Let Me Try

For show its ability of this function. I design a thread flow to show it as blew. Each thread prints some message so that we can check the programe excute order.

Created with Raphaël 2.1.0 Join Thread Demo MainThread MainThread Thread1 Thread1 Thread2 Thread2 start thread 1 join thread 1 start thread 2 invoke join() for thread 2 do something. End Notify thread 2 is finish to other threads. Main Thread still blocks because thread 1 hasn't finished. Thread 1 can run after thread 2 has finished. Do someting End Notify thread 1 is finish to other threads. Main thread can run after that. Do something End Programe end.
    /**
     * Simple way to let t1 stop before t2
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread() {
            public void run() {
                System.out.println("Thread 1 start.");
                Thread t2 = new Thread() {
                    public void run() {
                        System.out.println("Thread 2 start.");

                        try {
                            //Simulate t2 do a long action
                            System.out.println("Thread 2 is busy.");
                            Thread.sleep(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        System.out.println("Thread 2 finish.");
                    }
                };
                t2.start();

                try {
                    t2.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println("Thread 1 finish.");
            }
        };
        t1.start();
        t1.join();
        System.out.println("Main thread finish.");
    }
}

Welcome to My Home

In resource code, there is a while loop for check thread status. If thread’s status is alive ( isAlive() ), it will invoke wait() method to wait a few time until other thread call notify function or inter

    /**
     * Waits at most {@code millis} milliseconds for this thread to
     * die. A timeout of {@code 0} means to wait forever.
     *
     * <p> This implementation uses a loop of {@code this.wait} calls
     * conditioned on {@code this.isAlive}. As a thread terminates the
     * {@code this.notifyAll} method is invoked. It is recommended that
     * applications not use {@code wait}, {@code notify}, or
     * {@code notifyAll} on {@code Thread} instances.
     *
     * @param  millis
     *         the time to wait in milliseconds
     *
     * @throws  IllegalArgumentException
     *          if the value of {@code millis} is negative
     *
     * @throws  InterruptedException
     *          if any thread has interrupted the current thread. The
     *          <i>interrupted status</i> of the current thread is
     *          cleared when this exception is thrown.
     */
    public final synchronized void join(long millis)
    throws InterruptedException {
        long base = System.currentTimeMillis();
        long now = 0;

        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (millis == 0) {
            while (isAlive()) {
                wait(0);
            }
        } else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值