zoukankan      html  css  js  c++  java
  • CyclicBarrier&CountDownLatch&Semaphore

    CyclicBarrier示例:

    每调用一次barrier.await(), barrier的counter就减一,直到减到0,线程执行。所以CyclicBarrier的作用就是使一组线程一起到达某个点的时候同时执行。

    package com.ivy.thread;
    
    import java.util.concurrent.BrokenBarrierException;
    import java.util.concurrent.CyclicBarrier;
    
    class CyclicBarrierWork implements Runnable {
    
        private int id;
        private CyclicBarrier barrier;
        
        public CyclicBarrierWork(int id, final CyclicBarrier barrier) {
            this.id = id;
            this.barrier = barrier;
        }
        
        @Override
        public void run() {
            // TODO Auto-generated method stub
                
                try {
                    System.out.println(id + " Thread");
                    barrier.await();
                } catch (InterruptedException|BrokenBarrierException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } 
        }
        
    }
    public class TestCyclicBarrier {
    
        public static void main(String[] args) {
            int num = 10;
            CyclicBarrier barrier = new CyclicBarrier(num, new Runnable() {
                
                @Override
                public void run() {
                    System.out.println("finished");
                    
                }
            });
    
            for(int i=0;i<num;i++) {
                new Thread(new CyclicBarrierWork(i, barrier)).start();
            }
        }
    
    }

    CountDownLatch示例:

    只有CountDownLatch减到0,线程才开始执行,所以可以使一个线程等待另一个线程执行完后再执行。

    package com.ivy.thread;
    
    import java.util.concurrent.CountDownLatch;
    
    public class TestHarness {
    
        public long timeTasks(int nThreads, final Runnable task) throws InterruptedException {
            final CountDownLatch startGate = new CountDownLatch(1);
            final CountDownLatch endGate = new CountDownLatch(nThreads);
            
            for(int i = 0; i < nThreads; i++) {
                Thread t = new Thread() {
                    public void run() {
                        try {
                            startGate.await();
                            try {
                                task.run();
                            } finally {
                                endGate.countDown();
                            }
                        } catch (InterruptedException ignored) {}
                    }
                };
                t.start();
            }
            long start = System.nanoTime();
            startGate.countDown();
            endGate.await();
            long end = System.nanoTime();
            return end-start;
        }
        
        public static void main(String[] args) {
            Runnable task = new Runnable() {
                
                @Override
                public void run() {
                    System.out.println("haha");
                    
                }
            };
            
            try {
                long interval = new TestHarness().timeTasks(3, task);
                System.out.println(interval);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    Semaphore示例:

    Semaphore就是一个信号量,它的作用是限制某段代码块的并发数。Semaphore有一个构造函数,可以传入一个int型整数n,表示某段代码最多只有n个线程可以访问,如果超出了n,那么请等待,等到某个线程执行完毕这段代码块,下一个线程再进入。由此可以看出如果Semaphore构造函数中传入的int型整数n=1,相当于变成了一个synchronized了。

    package com.ivy.thread;
    
    import java.util.Collections;
    import java.util.HashSet;
    import java.util.Set;
    import java.util.concurrent.Semaphore;
    
    public class BoundedHashSet<T> {
    
        private final Set<T> set;
        private final Semaphore sem;
        
        public BoundedHashSet(int bound) {
            this.set = Collections.synchronizedSet(new HashSet<T>());
            sem = new Semaphore(bound);
        }
        
        public boolean add(T o) throws InterruptedException {
            sem.acquire();
            boolean wasAdded = false;
            try {
                wasAdded = set.add(o);
            } finally {
                if (!wasAdded) {
                    sem.release();
                }
            }
            return wasAdded;
        }
        
        public boolean remove(Object o) {
            boolean wasRemoved = set.remove(o);
            if (wasRemoved) {
                sem.release();
            }
            return wasRemoved;
        }
    }
  • 相关阅读:
    倍增_ST表与LCA
    树状数组
    CF1365B 题解
    左偏树
    ES5_04_Array扩展
    ES5_03_Object扩展
    ES5_05_Function扩展
    前台样式与实际开发应用
    利用Mircosoft URLRewriter.dll实现页面伪静态(伪静态系列一)
    递归算法常见习题代码(控制台程序)
  • 原文地址:https://www.cnblogs.com/IvySue/p/7492224.html
Copyright © 2011-2022 走看看