java多线程编程之Semaphore

Posted 天空中的蜂蜂

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

java并发编程之Semaphore

java 多线程 28 : 多线程组件之 Semaphore 信号量

java多线程之Concurrent.Utils常用类Semaphore详解

Java多线程之JUC包:Semaphore源码学习笔记

Java并发多线程编程——并发工具类Semaphore(信号量)

Java多线程系列--“JUC锁”11之 Semaphore信号量的原理和示例