SemaphoreTest

来源:互联网 发布:oracle生成json格式化 编辑:程序博客网 时间:2024/05/20 18:20
package com.ixhong.base.thread;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Semaphore;public class SemaphoreTest {   public static void main(String[] args) {      ExecutorService service = Executors.newCachedThreadPool();      final  Semaphore sp = new Semaphore(3);      for(int i=0;i<10;i++){         Runnable runnable = new Runnable(){               public void run(){               try {                  sp.acquire();               } catch (InterruptedException e1) {                  e1.printStackTrace();               }               System.out.println("线程" + Thread.currentThread().getName() +                      "进入,当前已有" + (3-sp.availablePermits()) + "个并发");               try {                  Thread.sleep((long)(Math.random()*10000));               } catch (InterruptedException e) {                  e.printStackTrace();               }               System.out.println("线程" + Thread.currentThread().getName() +                      "即将离开");                              sp.release();               //下面代码有时候执行不准确,因为其没有和上面的代码合成原子单元System.out.println("线程" + Thread.currentThread().getName() +                      "已离开,当前已有" + (3-sp.availablePermits()) + "个并发");                           }         };         service.execute(runnable);             }   }}线程pool-1-thread-1进入,当前已有2个并发线程pool-1-thread-3进入,当前已有3个并发线程pool-1-thread-2进入,当前已有2个并发线程pool-1-thread-2即将离开线程pool-1-thread-2已离开,当前已有2个并发线程pool-1-thread-4进入,当前已有3个并发线程pool-1-thread-4即将离开线程pool-1-thread-4已离开,当前已有2个并发线程pool-1-thread-5进入,当前已有3个并发线程pool-1-thread-1即将离开线程pool-1-thread-1已离开,当前已有2个并发线程pool-1-thread-6进入,当前已有3个并发线程pool-1-thread-3即将离开线程pool-1-thread-3已离开,当前已有2个并发线程pool-1-thread-7进入,当前已有3个并发线程pool-1-thread-5即将离开线程pool-1-thread-5已离开,当前已有3个并发线程pool-1-thread-8进入,当前已有3个并发线程pool-1-thread-6即将离开线程pool-1-thread-6已离开,当前已有2个并发线程pool-1-thread-9进入,当前已有3个并发线程pool-1-thread-9即将离开线程pool-1-thread-9已离开,当前已有2个并发线程pool-1-thread-10进入,当前已有3个并发线程pool-1-thread-10即将离开线程pool-1-thread-10已离开,当前已有2个并发线程pool-1-thread-7即将离开线程pool-1-thread-7已离开,当前已有1个并发线程pool-1-thread-8即将离开线程pool-1-thread-8已离开,当前已有0个并发

java api中Semaphore(信号量),用于控制有限资源的并发访问。API也非常好理解,不过有几个需要注意的地方:

  1. Semaphore是纯粹的应用级控制“锁”,使用简单的volitale变量作为信号量信息,通过acquire、release、reduce等显式的可以修改此信号量数字。
  2. 它并没有维护任何锁,也不是控制reentrant的,它不会维护信号和thread的关系。
  3. Semaphore的初始值可以为0,甚至可以为负数。对于acquire调用(信号down),它只会比较现在信号值与0的大小关系,如果<=0那么将不能获得授权。
  4. 对于release(信号up),只是简单的对信号值进行原子增加,经过多次的release,信号值可以超过初始的阀值。
  5. 对于Semaphore(0/-N)的场景,有特殊的使用,这种信号控制,在可以acquire之前,必须经过约定的足够多的release之后才可以被使用。

参考:http://stackoverflow.com/questions/1221322/how-does-semaphore-work

0 0
原创粉丝点击