java 多线程-信号量 Semaphore

Java信号量与线程池实战
本文通过一个Java示例程序介绍了如何使用信号量控制并发线程的数量,并结合线程池来管理这些线程。具体实现了信号量的获取与释放,确保了线程在指定数量限制下有序执行。

public class Test{
	public static void main(String[] arg){
		Semaphore semaphore = new Semaphore(3);//定义信号量
		//SecurityManager sm = System.getSecurityManager();
		//ThreadGroup group = sm == null ? Thread.currentThread().getThreadGroup() : sm.getThreadGroup();
		ThreadGroup group = new ThreadGroup("semaphore");//自定义线程组
		AtomicInteger num = new AtomicInteger(0);

		ThreadPoolExecutor pool = new ThreadPoolExecutor(
				5, 
				8, 
				1000, 
				TimeUnit.SECONDS, 
				new LinkedBlockingDeque<Runnable>(20), new ThreadFactory() {//线程池工厂
					@Override
					public Thread newThread(Runnable r) {//生产新的线程
						Thread thread = new Thread(group, r, group.getName()+"-thread-"+num.getAndIncrement());
						thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
							@Override
							public void uncaughtException(Thread t, Throwable e) {
								System.out.println(t.getName()+"发生异常:"+e.getMessage());
							}
						});
						return thread;
					}
				},new RejectedExecutionHandler() {//线程池的拒绝策略
					@Override
					public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
						throw new RuntimeException("任务队列已满,任务被拒绝");
					}
				});

		//定义任务
		Runnable task = ()->{
			try {
				semaphore.acquire();
				System.out.println(Thread.currentThread().getName()+"已获得信号量许可,正在运行");
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}finally {
				semaphore.release();
			}
		};

		for(int i = 0; i < 10; i++){//循环运行10个任务
			pool.execute(task);
		}

		if(Thread.activeCount() > 1){
			Thread.yield();
		}
		pool.shutdown();
	}
}

信号量就像是一个资源控制器,在任意时刻,只有获得信号量资源的线程才会运行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值