首页 > 编程语言 > 详细

java多线程编程之Semaphore

时间:2016-10-19 19:35:42      阅读:187      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/fengfengtk/p/5978308.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!