Semaphore信号量的学习笔记

       咱们知道独占锁能够实现临界资源一次只能被一个线程访问,但若是想实现多个线程同时访问的话就要用到信号量Semaphore——记录一个共享资源被访问线程的个数,Semeahore更像是一个共享锁,当它的许可数为1的时候就至关于独占锁了;acquire(int n)拿许可,一次可拿多个、tryAcquire()尝试拿许可boolean,也可设置尝试获取时间、release()释放许可;ide

public class SamephoreDemo {
   static  Semaphore sema=new Semaphore(2);
    public static class task implements Runnable{
        @Override
        public void run() {
            try {
                sema.acquire();//拿许可
                Thread.sleep(2000);//模拟耗时
                System.out.println(Thread.currentThread().getName()+"完成");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                sema.release();//释放许可
            }
        }
    }
    public static void main(String[] args) {
        ExecutorService executorService=Executors.newFixedThreadPool(8);
        for(int i=0;i<16;i++){
            executorService.submit(new task());
        }
    }
}
执行结果:每隔2s左右打印2条信息
pool-1-thread-1完成
pool-1-thread-2完成
pool-1-thread-4完成
pool-1-thread-1完成
pool-1-thread-1完成
pool-1-thread-4完成
pool-1-thread-3完成
pool-1-thread-4完成
pool-1-thread-3完成
pool-1-thread-4完成
pool-1-thread-5完成
pool-1-thread-7完成
pool-1-thread-6完成
pool-1-thread-8完成
pool-1-thread-1完成
pool-1-thread-2完成

解析:咱们定义了一个许可数为2的信号量,一次最多两个线程同时执行,故执行结果是每隔2s左右打印2条信息。ui

相关文章
相关标签/搜索