标签:exce 比较 fixed tar service print 失败 lock 信号量
public Semaphore(int permits) public Semaphore(int permits, boolean fair)//第二个参数可以指定是否公平
public void acquire()//尝试获得一个准入的许可,若无法获得,等待直到有线程释放一个或者中断. public void acquireUninterruptibly()//和acquire()差不多,只是不响应中断, public boolean tryAcquire()//试图去获取一个许可,成功立即返回true 失败立即false public boolean tryAcquire(long timeout, TimeUnit unit)//规定一个等待时间,超时就false public void release()//释放一个许可.
public class SemapDemo implements Runnable { final Semaphore semp = new Semaphore(5);//允许五个许可 /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object‘s * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see Thread#run() */ @Override public void run() { try { semp.acquire(); Thread.sleep(2000); System.out.println(Thread.currentThread().getId() + ":done!"); semp.release(); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { ExecutorService exec = Executors.newFixedThreadPool(20);//容量为20的线程池 final SemapDemo demo = new SemapDemo(); for (int i = 0; i < 20; i++) { exec.submit(demo); } } }
标签:exce 比较 fixed tar service print 失败 lock 信号量
原文地址:http://www.cnblogs.com/ten951/p/6212132.html