Java高并发程序-Chapter3 JDK并发包(第十四讲)同步控制之自己动手实现 CoutDownLatch

这里我们自己动手实现 CoutDownLatch,使用LockSupport 和 等待队列, 如何无法理解,可以学习 《ReentrantLock 的实现》

package com.john.learn.high.concurent.ch03.tools;

import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;

public class CountDownLatch {

	private AtomicInteger count;

	private int _startCount;
        //挂起线程Queue
	private ConcurrentLinkedQueue<Thread> threadQueue = new ConcurrentLinkedQueue<Thread>();

	public CountDownLatch(int count) {
		this.count = new AtomicInteger(count);
		_startCount = count;
	}

	public void await() throws InterruptedException {
                 //如果完成,不用park当前线程
		if (this.count.get() == 0) {

			return;
		}
                //当前Thread加入Queue 
		threadQueue.add(Thread.currentThread());
                //然后挂起线程
		LockSupport.park(this);

		if (Thread.interrupted()) {

			throw new InterruptedException();
		}

	}

	public void countDown() {

		int _count = count.decrementAndGet();
                //如果所有线程完成工作,激活park的线程。
		if (_count == 0) {

			Thread thread = null;

			while ((thread = threadQueue.poll()) != null) {

				if (thread.isInterrupted() || !thread.isAlive()) {
					continue;
				}

				LockSupport.unpark(thread);

			}

		}
	}

	public int getCount() {
		return _startCount;
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值