多线程学习01:Semaphore信号量的用法

Semaphore,信号量,是用来控制并发数量的有效手段。通常我们可以把他理解成一个带有固定容量许可的池子。当需要做一件事情,首先需要向池子里申请许可(permit)。当池子中还有空闲许可的时候,可以申请成功,获得许可,意味着可以接下来执行要的事情,否则会阻塞直到获得腾出来的许可。当执行完操作时,需要释放掉许可。
申请许可 和 释放许可 对应方法:acquire和release。acquire可以申请多个,同样的release也可以释放多个。但是注意,释放超过申请的,会使得整个许可集中许可的数量变多。另外,可以通过tryAcquire的几个方法来尝试获取许可,见下文代码示例:

package org.zheng.multithread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 信号量
 * Create by zxb on 2017/4/26
 */
public class SemaphoreTest {

    private static final int THREAD_COUNT = 5;

    private static ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT);

    private static Semaphore s = new Semaphore(3);

    /**
     * tryAcquire()
     * 尝试获取permits个许可,成功则返回true,失败则返回false
     *
     * @throws InterruptedException
     */
    public static void testTryAcquire1() throws InterruptedException {
        if (s.tryAcquire()) {  //尝试获取一个许可
            System.out.println(Thread.currentThread().getName() + " 获得许可");
            Thread.sleep(1500);
            System.out.println(Thread.currentThread().getName() + " 操作完毕");
            s.release();   //释放许可证
        } else {
            System.out.println(Thread.currentThread().getName() + "未获得许可");
        }
    }

    /**
     * tryAcquire(int permits)
     * 尝试获取permits个许可,成功则返回true,失败则返回false
     *
     * @throws InterruptedException
     */
    public static void testTryAcquire2() throws InterruptedException {
        if (s.tryAcquire(1)) {  //尝试获取一个许可
            System.out.println(Thread.currentThread().getName() + " 获得许可");
            Thread.sleep(1500);
            System.out.println(Thread.currentThread().getName() + " 操作完毕");
            s.release();   //释放许可证
        } else {
            System.out.println(Thread.currentThread().getName() + "未获得许可");
        }
    }

    /**
     * tryAcquire(long timeout, TimeUnit unit)
     * 设置超时时间内能获取到1个许可都会返回true,否则返回false
     *
     * @throws InterruptedException
     */
    public static void testTryAcquire3() throws InterruptedException {
        if (s.tryAcquire(1, TimeUnit.SECONDS)) {   //尝试获取一个许可,超时时间1s
            System.out.println(Thread.currentThread().getName() + " 获得许可");
            Thread.sleep(3000);
            System.out.println(Thread.currentThread().getName() + " 操作完毕");
            s.release();   //释放许可证
        } else {
            System.out.println(Thread.currentThread().getName() + "未获得许可");
        }
    }

    /**
     * 不断尝试,直到都获取到信号量执行任务
     *
     * @throws InterruptedException
     */
    public static void testTryAcquire4() throws InterruptedException {
        while (true) {
            if (s.tryAcquire(1, TimeUnit.SECONDS)) {
                System.out.println(Thread.currentThread().getName() + " 获得许可");
                Thread.sleep(3000);
                System.out.println(Thread.currentThread().getName() + " 操作完毕");
                s.release();   //释放许可证
                break;
            }
        }
    }

    /**
     * 常规用法,先获取,获取不到则阻塞线程执行,获取到执行完,释放信号量
     *
     * @throws InterruptedException
     */
    public static void testAcquire() throws InterruptedException {
        s.acquire();    //获取许可
        System.out.println(Thread.currentThread().getName() + " 获得许可");
        Thread.sleep(1000);
        System.out.println(Thread.currentThread().getName() + " 操作完毕");
        s.release();   //释放许可,只需要释放一次,释放多次会让信号量多增加
    }

    public static void main(String[] args) {
        for (int i = 0; i < THREAD_COUNT; i++) {
            threadPool.execute(new Runnable() {

                @Override
                public void run() {
                    try {
//                        testTryAcquire1();
//                        testTryAcquire2();
//                        testTryAcquire3();
//                        testTryAcquire4();
                        testAcquire();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        threadPool.shutdown();
    }
}

执行结果:


信号量的作用可以看到,同时最多3个线程在跑,其他2个线程就阻塞在等待获取中,当有释放许可,可以立即被等待线程获取到,然后继续进行操作。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值