Section III. Concurrent Programming Tools + countDownLatch + Semaphore

JUC Programming Tools

It contains five tools: Excutors , Semaphore , Exchanger, CyclicBarrier , CountDownLatch 

 

 

 

Semaphore

            For flow control , limit the maximum number of concurrent access concurrent. A common resource pool definition X permit
            shared locks, lock unfair ===>    STATE (AQS)

 

 

Semaphore common method

  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();

For example 

SemaphoreSample.java

Import java.util.concurrent.Semaphore;
 Import java.util.concurrent.TimeUnit; 

/ ** 
 * @description: can be used for flow control, limits the maximum number of concurrent access 
 * / 
public  class SemaphoreSample { 

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

    static  class Task the extends the 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

 

 

 

Guess you like

Origin www.cnblogs.com/qianbing/p/12596020.html