码迷,mamicode.com
首页 > 编程语言 > 详细

java多线程编程之Semaphore

时间:2016-10-19 19:38:42      阅读:221      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!