JavaDemo——并发工具之Semaphore

许可管理?有点像锁,拿到许可往下执行,拿不到阻塞,最后释放许可。

Demo:

/**
 * 2019年8月9日上午10:04:41
 */
package testThreadUtil.testSemaphore;

import java.util.concurrent.Semaphore;
import java.util.stream.IntStream;

/**
 * @author XWF
 *
 */
public class TestSemaphore {
	
	private static Semaphore semaphore = new Semaphore(3);//设定初始值,可为负数(默认不公平策略)
//	private static Semaphore semaphore = new Semaphore(3, true);//可指定是否用公平FIFO策略

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		IntStream.range(1,6).forEach(i -> testThread(i));
		
//		semaphore.acquire();//有可用许可时获得许可,许可数-1,否则阻塞等待(中断会抛出InterruptedException)
//		semaphore.acquire(permits);//获得指定个数的许可(InterruptedException)
//		semaphore.acquireUninterruptibly();//如果被中断不会抛出异常,继续等待
//		semaphore.acquireUninterruptibly(permits);//获得指定个数
//		semaphore.availablePermits();//返回当前可用许可数
//		semaphore.drainPermits();//返回当前可用许可,并将许可数置为0
//		semaphore.getQueueLength();//等待线程队列长度
//		semaphore.hasQueuedThreads();//是否有在等待的线程
//		semaphore.isFair();//是否是公平的FIFO
//		semaphore.release();//释放许可,许可数+1(由程序约束释放量)
//		semaphore.release(permits);//释放多个许可
//		semaphore.tryAcquire();//得到许可返回true,否则返回false,不阻塞,不按公平策略
//		semaphore.tryAcquire(permits);//多个许可
//		semaphore.tryAcquire(timeout, unit);//指定等待时间,时间内获得返回true,超时获得不到返回false(InterruptedException)
//		semaphore.tryAcquire(permits, timeout, unit);//指定等待时间和获得许可数(InterruptedException)
	}

	public static void testThread(final int i) {
		try {
			Thread.sleep(150);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		new Thread(() -> {
			try {
				System.out.println(i + " 准备获得许可");
				semaphore.acquire();
				System.out.println(i + "-得到许可。");
				int available = semaphore.availablePermits();
				System.out.println(i + " 当前剩余:" + available);
				System.out.println(i + " 是否有等待队列:" + semaphore.hasQueuedThreads());
				System.out.println(i + " 等待队列长度:" + semaphore.getQueueLength());
				Thread.sleep(1000);
				System.out.println(i + "-释放许可。");
				semaphore.release();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}).start();
	}
}

结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值