首页 > 代码库 > java多线程编程之Semaphore
java多线程编程之Semaphore
java.util.concurrent.Semaphore这个类里面的主要方法为:
void acquire():Acquires a permit from this semaphore, blocking until one is available, or the thread isinterrupted.
boolean tryAcquire():Acquires a permit from this semaphore, only if one is available at the time of invocation.
void release(): Releases a permit, returning it to the semaphore.
//Test.java import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import java.util.concurrent.Semaphore; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub ExecutorService execSer = Executors.newCachedThreadPool(); final Semaphore sem = new Semaphore(3); for (int i = 0; i < 12; i++) { final int NO = i; Runnable run = new Runnable(){ public void run() { try { sem.acquire(); Thread.sleep(1000); System.out.println("Runnable :"+NO); sem.release(); System.out.println("---"+sem.availablePermits()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; execSer.execute(run); } execSer.shutdown(); } }
java多线程编程之Semaphore
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。