• 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;
        }
    }
  • 相关阅读:
    剑指 Offer 22. 链表中倒数第k个节点(简单)
    剑指 Offer 18. 删除链表的节点(简单)
    Proxy error: Could not proxy request
    剑指 Offer 63. 股票的最大利润(中等)
    剑指 Offer 47. 礼物的最大价值(中等)
    剑指 Offer 42. 连续子数组的最大和(简单)
    oracle 常用函数之 字符函数
    oracle 常用函数之 日期函数
    oracle 常用函数之聚合函数
    jdbc
  • 原文地址:https://www.cnblogs.com/IvySue/p/7492224.html
Copyright © 2020-2023  润新知