java多线程Thread join与CountDownLatch源码分析

1、Thread join方法详解

首先,对于JAVA的一些基础知识,工作年限到了一定时间后,尽量不要一来就百度查询,比如thread join的作用,我们不妨先看一看join方法的源码,先试着自己理解,然后再去查询别人的理解,举一反三,美哉美哉。

join方法的声明与源码如下:

/**
     * Waits at most {@code millis} milliseconds for this thread to
     * die. A timeout of {@code 0} means to wait forever.
     *
     * 

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 * interrupted status 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; } } }

首先,join方法是线程对象的实例方法,并不同于sleep方法。并且被 synchronized关键字被修饰,说明要进入join方法,必须获得线程的对象锁。所以join(long millis)方法,指的是获取对象锁后需要等待的时间,并不是join方法等待的时间。

join的方法是在a线程中,调用 b.join()方法,实现的语义是,线程a等待线程b执行完毕后,再执行;join方法支持中断。实现的原理是在线程处于激活状态(isActive())方法时,调用 wait 方法或 wait(long milliseconds)方法。下面提供三个测试方法,进一步说明join方法语义:

package persistent.prestige.study.thread;
/**
 * t.join学习
 * @author dingwei2
 *
 */
public class JoinThread {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        // test1();

        // test2();

        test3();


    }

    /**
     * 测试 join的基本语义,在其他线程执行完毕后,主线程才会结束
     * 
     * 该测试用例说明:
     * 如果将t1.join 注释掉,则输出基本是
     *     main 线程启动.....
     *     main 线程结束......
     *         1
     *         2
     *         3
     * 如果增加t1.join则,主线程需要等待 t1线程运行结束后,才会退出,输出如下:
     *     main 线程启动.....
     *            1
     *         2
     *         3
     *     main 线程结束......
     */
    public static void test1() {
        System.out.println("main 线程启动.....");
        Thread t1 = new Thread(new RunThread1());
        t1.start();

        try {
            t1.join(); // @1
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("main 线程结束......");
    }


    /**
     * 测试 t1.join(long miliseconds) 方法
     */
    public static void test2() {
        System.out.println("main 线程启动.....");
        Thread t1 = new Thread(new RunThread2());
        t1.start();

        try {
            t1.join(3000); // @1
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("main 线程结束......");
    }

    public static void test3() {
        System.out.println("main 线程启动.....");
        Thread t1 = new Thread(new RunThread1());
        Thread t2 = new Thread(new RunThread3(t1));
        t1.start();
        t2.start();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }//确认t1,t2都在运行


        try {
            long start = System.currentTimeMillis();
            t1.join(1000);
            long end = System.currentTimeMillis();
            System.out.println("join方法执行后,经过" + ((end - start) / 1000) + "秒结束"); //这里不是1秒,需要等线程t2执行完毕才能被唤醒,
                                                                               //为什么呢,因为在线程t2中,占用了t1线程的对象锁,t1.join首先需要获取t1的对象锁。所以需要等t2执行完毕,                              
                                                                              //释放锁后才能开始执行join方法。
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("main 线程结束......");

    }

}

class RunThread1 implements Runnable {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        for(int i =0; i < 5; i ++) {
            System.out.println(Thread.currentThread().getName() + ":输出" + i);
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

} 


class RunThread2 implements Runnable {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        for(int i =0; i < 5; i ++) {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + ":输出" + i);
        }

    }

} 

class RunThread3 implements Runnable {

    private Thread t;
    public RunThread3(Thread t) {
        this.t = t;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        synchronized(t) {
            for(int i =0; i < 5; i ++) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + ":输出" + i);
            }
        }


    }

} 

2、CountDownLatch源码分析

CountDownLatch,闭锁,能够实现Thread join 类似的语义,用在如下业务场景,比如协调者(主线程)创建多个线程去并发的完成一件事情,主线程创建并启动线程后,需要等待任务全部运行完毕后,主线程处理相关事情后再退出。

如下代码是我们经常会看到的。

public static void main(String[] args) throws Exception {
    System.out.println("测试开始。。");
    for(int i = 0; i < 30; i ++) {
            new Thread(  new ThreadA()).start();//处理任务
    }    
    
    //为了防止主线程提早退出,我们一般会让主线程sleep,
    Thread.sleep(100* 1000);  //这种不准确,实现方法不友好。
   
    System.out.println("测试结束")
}
为了解决上述问题,CountDownLatch 能精确的解决上述问题。
CountDownLatch使用实例:
public class RunnalA implements Runnable {
    private CountDownLatch cdl;
    public RunnalA (CountDownLatch cdl) {
        this.cdl=cdl;
    }

    public void run() {
         for(int i = 0; i < 20;i++) {
                System.out.println("i:"+i);
          }
         // 线程运行完毕后,
         cdl.countDown();
    }
}

public class MainCls {
    public static void main(String[] args) throws InterruptException {
        CountDownLatch  cdl = new CountDownLatch(10); 
        for(int i =0; i < 10; i++ ) {
            new Thread(new RunnalA(cdl) ).start();
        }
       //需要等10个线程全部运行完毕后,主线程才结束
       cdl.await();//等10个线程运行完毕后,主线程才会退出。
    }
}

2.1 CountDownLatch 方法实现原理

首先,通过CountDownLatch的构造方法,设置锁的state变量,从分析ReentrantLock,ReentrantReadWriteLock 中我们应该知道state的意义。

然后await方法,使用获取共享锁的模式,由于state不为,则await方法调用,必然会在CLH队列中增加一个节点,然后线程阻塞。

countDown方法,每次将state减1,直到state=0时,唤醒线程,awiat方法成功获取锁,方法解除阻塞,继续执行。源码的分析就不做过多的解读,因为如下代码在学习ReentrantLock,ReentrantReadWriterLock锁时已经详细分析了。

CountDownLatch对tryAcquireSharedd的实现,是 
return (getState() == 0) ? 1 : -1;  如果getState()的值为0,则不阻塞,直接返回。如果state大于0,则在CLH队列中等待,由于我们在使用的时候,一定是先调用await方法,这样await方法在调用的时候,肯定是获取不到锁的,故在CLH队列中,会是这样的结构  head-->Node[队列尾部,就是代表调用await方法的线程。]

CountDownLatch的 countDown方法,内部就是调用releaseShared方法。
public final boolean releaseShared(int arg) {
        if (tryReleaseShared(arg)) {
            doReleaseShared();
            return true;
        }
        return false;
    }
protected boolean tryReleaseShared(int releases) { //如果 state或减去1之后的值为0,则返回ture,表明可以唤醒由于调用                                                                                  //await方法调用的线程
            // Decrement count; signal when transition to zero
            for (;;) {
                int c = getState();
                if (c == 0)
                    return false;
                int nextc = c-1;
                if (compareAndSetState(c, nextc))
                    return nextc == 0;
            }
        }
private void doReleaseShared() {
        /*
         * Ensure that a release propagates, even if there are other
         * in-progress acquires/releases.  This proceeds in the usual
         * way of trying to unparkSuccessor of head if it needs
         * signal. But if it does not, status is set to PROPAGATE to
         * ensure that upon release, propagation continues.
         * Additionally, we must loop in case a new node is added
         * while we are doing this. Also, unlike other uses of
         * unparkSuccessor, we need to know if CAS to reset status
         * fails, if so rechecking.
         */
        for (;;) {
            Node h = head;
            if (h != null && h != tail) {
                int ws = h.waitStatus;
                if (ws == Node.SIGNAL) {
                    if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
                        continue;            // loop to recheck cases
                    unparkSuccessor(h);
                }
                else if (ws == 0 &&
                         !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
                    continue;                // loop on failed CAS
            }
            if (h == head)                   // loop if head changed
                break;
        }
    }

欢迎加笔者微信号(dingwpmz),加群探讨,笔者优质专栏目录:

1、源码分析RocketMQ专栏(40篇+)
2、源码分析Sentinel专栏(12篇+)
3、源码分析Dubbo专栏(28篇+)
4、源码分析Mybatis专栏
5、源码分析Netty专栏(18篇+)
6、源码分析JUC专栏
7、源码分析Elasticjob专栏
8、Elasticsearch专栏
9、源码分析Mycat专栏

 

 

 

 

 

你可能感兴趣的:(java并发编程)