使用CountDownLaunch模拟并发

 

CountDownLatch是通过一个计数器来实现的,计数器的初始值为线程的数量。每当一个线程完成了自己的任务后,计数器的值就会减1。当计数器值到达0时,它表示所有的线程已经完成了任务,然后在闭锁上(调用CountDowmLaunch.await()的线程)等待的线程就可以恢复执行任务。

public class Test3 {

    public static void main(String[] args) throws InterruptedException {
        final AtomicInteger atomicInteger = new AtomicInteger();
        final Integer[] ii = {0};
        final CountDownLatch latch1 = new CountDownLatch(1000);
        final CountDownLatch latch2 = new CountDownLatch(1000);

        for (int i = 0; i < 1000; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 阻塞所有线程
                        latch1.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    for (int j = 0; j < 1000; j++) {
                        // ii[0] = ii[0] + 1;
                        atomicInteger.incrementAndGet();
                    }
                    latch2.countDown();
                }
            }).start();
            // 每次启动一个线程countDownLaunch减1,当启动1000个之后,countdownLaunch减为0,所有阻塞线程开始执行
            latch1.countDown();
        }

        // 阻塞主线程等待所有线程执行完成
        latch2.await();
        // System.out.println("finish , ii[0] = " + ii[0]);                 //finish , atomicInteger = 612613
        System.out.println("finish , atomicInteger = " + atomicInteger);    //finish , atomicInteger = 1000000
    }
}

CountDownLaunch内部维护了一个

private final Sync sync;

Sync是实现AbstractQueuedSynchronizer的内部类,内部与Lock锁机制类似,有一个state字段,为0代表没有加锁,大于0的次数代表加锁的次数。

public void countDown() {
   sync.releaseShared(1);
}
public final boolean releaseShared(int arg) {
     if (tryReleaseShared(arg)) {
        doReleaseShared();
        return true;
     }
   return false;
}
 protected boolean tryReleaseShared(int releases) {
    // Decrement count; signal when transition to zero
       for (;;) {
          int c = getState();    // 获取state 表示加锁次数
          if (c == 0)
              return false;   // state为0代表没有加锁
          int nextc = c-1;
          if (compareAndSetState(c, nextc))    //使用cas更新state减一,返回true代表更新更改,否则循环
             return nextc == 0;
      }
}
    public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }
    public final void acquireSharedInterruptibly(int arg)
            throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
        if (tryAcquireShared(arg) < 0)    // 如果state=0返回1返回false,不阻塞线程
            doAcquireSharedInterruptibly(arg);
    }
    protected int tryAcquireShared(int acquires) {
        return (getState() == 0) ? 1 : -1;
    }
    // 以共享可中断模式获取。
    private void doAcquireSharedInterruptibly(int arg)
        throws InterruptedException {
        final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            for (;;) {
                final Node p = node.predecessor();
                if (p == head) {
                    int r = tryAcquireShared(arg);
                    if (r >= 0) {
                        setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        failed = false;
                        return;
                    }
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }
    public boolean await(long timeout, TimeUnit unit)
        throws InterruptedException {
        return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
    }
    public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout)
            throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
        return tryAcquireShared(arg) >= 0 ||
            doAcquireSharedNanos(arg, nanosTimeout);
    }
    private boolean doAcquireSharedNanos(int arg, long nanosTimeout)
            throws InterruptedException {
        if (nanosTimeout <= 0L)
            return false;
        final long deadline = System.nanoTime() + nanosTimeout;
        final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            for (;;) {
                final Node p = node.predecessor();
                if (p == head) {
                    int r = tryAcquireShared(arg);
                    if (r >= 0) {
                        setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        failed = false;
                        return true;
                    }
                }
                nanosTimeout = deadline - System.nanoTime();
                if (nanosTimeout <= 0L)
                    return false;    // 超时,直接返回false,也不阻塞线程
                if (shouldParkAfterFailedAcquire(p, node) &&
                    nanosTimeout > spinForTimeoutThreshold)
                    LockSupport.parkNanos(this, nanosTimeout);
                if (Thread.interrupted())
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

 

你可能感兴趣的:(使用CountDownLaunch模拟并发)