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();
}
}
信号量就像是一个资源控制器,在任意时刻,只有获得信号量资源的线程才会运行