首页 > 其他分享 >信号量Semaphore

信号量Semaphore

时间:2022-10-12 17:44:11浏览次数:45  
标签:Thread currentThread Semaphore System 信号量 semaphore new

1.应用场景

对于多个线程来说,想要设计争抢有限的资源,可以用信号量来解决

2.代码

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(5);
        for (int i = 0; i < 20; i++) {
            final int index = i;
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        semaphore.acquire();
                        play();
                        semaphore.release();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    private static void play() {
        try {
            System.out.println(new Date()+Thread.currentThread().getName()+"获得紫禁之巅服务器进入资格");
            Thread.sleep(2000);
            System.out.println(new Date()+Thread.currentThread().getName()+"退出服务器");
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

 

对于信号量资源全被占用时,可以让没获取到的直接放行处理,可以用下面的方式,等待6s后6s之后的全部线程都放行

        ExecutorService executorService = Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(5);
        for (int i = 0; i < 20; i++) {
            final int index = i;
            executorService.execute(new Runnable() {
                @Override
                public void run() {

                    try {
//                        if (semaphore.tryAcquire()) {
                        if (semaphore.tryAcquire(6, TimeUnit.SECONDS)) {
                            play();
                            semaphore.release();
                        } else {
                            System.out.println(new Date() + Thread.currentThread().getName() + "服务器已满请稍后再试");
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    private static void play() {
        try {
            System.out.println(new Date() + Thread.currentThread().getName() + "获得紫禁之巅服务器进入资格");
            Thread.sleep(2000);
            System.out.println(new Date() + Thread.currentThread().getName() + "退出服务器");
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

 

标签:Thread,currentThread,Semaphore,System,信号量,semaphore,new
From: https://www.cnblogs.com/blanset/p/16785400.html

相关文章