JUC 并发包及其常用类

并发包体系结构:

 1. CountDownLatch

CountDownLatch 是一个同步工具类,用来协调多个线程之间的同步。
CountDownLatch 通过计数器来实现:使一个线程在等待另外一些线程完成各自工作后,再执行。计数器初始值为线程的数量。当每一个线程完成自己任务后,就通过 countDown()方法 将计数器减1。当计数器的值减为0时,表示其他所有线程都已经完成了各自的一些任务,然后在 CountDownLatch 上等待的线程就可以恢复执行接下来的任务。

方法源码:

/* @param count the number of times {@link #countDown} must be invoked
     *        before threads can pass through {@link #await}
     * @throws IllegalArgumentException if {@code count} is negative
     */
    public CountDownLatch(int count) {
        if (count < 0) throw new IllegalArgumentException("count < 0");
        this.sync = new Sync(count);
    }
/* Causes the current thread to wait until the latch has counted down to
 * zero, unless the thread is {@linkplain Thread#interrupt interrupted}.

 * @throws InterruptedException if the current thread is interrupted
 *         while waiting  */
public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

/**
 * Causes the current thread to wait until the latch has counted down to
 * zero, unless the thread is {@linkplain Thread#interrupt interrupted},
 * or the specified waiting time elapses.  */
public boolean await(long timeout, TimeUnit unit)
        throws InterruptedException {
        return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
    }

示例:

public class Test {
    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(3,3,10, TimeUnit.SECONDS,new LinkedBlockingDeque<Runnable>());
        CountDownLatch latch = new CountDownLatch(3);
        for (int i = 0; i < 3; i++) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("子线程" + Thread.currentThread().getName() + "开始执行");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("子线程"+Thread.currentThread().getName()+"执行完成");
                    latch.countDown();    //当前线程调用此方法,计数减一
                }
            });
        }
        {
            System.out.println("主线程" + Thread.currentThread().getName() + "等待子线程执行完成...");
            latch.await();//阻塞当前线程,直到计数器的值为0
            System.out.println("主线程" + Thread.currentThread().getName() + "开始执行...");
        }
    }

}

等待超时:如果某一个线程的操作耗时非常长或者发生了异常. * 但是并不想影响主线程的继续执行, 则可以使用await(long, TimeUnit)方法

2. Atomic原子类

Atomic包下装的是原子类,通过“原子性”操作实现变量在多线程下的线程安全

如果对变量进行加锁也可以保证线程安全,但抢不到锁线程会发生阻塞,线程上下文的切换会带来些许时延。

Atomic原子类的原理是通过CAS机制不断自旋,

 

未完待续~

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值