第三节. 并发编程之Tools+countDownLatch+Semaphore

JUC编程Tools

包含五个工具类: ExcutorsSemaphore、Exchanger、CyclicBarrierCountDownLatch 

Semaphore

            用于流量控制,限制最大的并发的并发访问数。公共资源池定义 X 个permit
            共享锁,非公平锁   ===>   STATE(AQS)

 

 

Semaphore 常用方法

  Semaphore semaphore  = new Semaphore(2);

  void semaphore.acquire(); 

  /* @param permits the number of permits to acquire
   * @param timeout the maximum time to wait for the permits
   * @param unit the time unit of the {@code timeout} argument */ 

  semaphore.tryAcquire(1, 1000, TimeUnit.MILLISECONDS);

  semaphore.release();

举例 

SemaphoreSample.java

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @description :可用于流量控制,限制最大的并发访问数
 */
public class SemaphoreSample {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(2);
        for (int i=0;i<5;i++){
            new Thread(new Task(semaphore,"yangguo+"+i)).start();
        }
    }

    static class Task extends Thread{
        Semaphore semaphore;

        public Task(Semaphore semaphore,String tname){
            this.semaphore = semaphore;
            this.setName(tname);
        }

        public void run() {
            try {
                // semaphore.tryAcquire(1,  1000, TimeUnit.MILLISECONDS);
                semaphore.tryAcquire();
                System.out.println(Thread.currentThread().getName()+":aquire() at time:"+System.currentTimeMillis());

                Thread.sleep(1000);
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}
View Code

 

猜你喜欢

转载自www.cnblogs.com/qianbing/p/12596020.html