Java:多线程,Semaphore同步器

1. 背景

类java.util.concurrent.Semaphore提供了一个计数信号量。通过Semaphore类,可以控制某个资源可被同时访问的个数,通过 acquire() 获取一个许可,如果没有就等待,而 release() 释放一个许可。

Semaphore的构造函数中带有一个fairness的参数,用于设置是否“公平”。当fairness为true时,Semaphore保证各线程以后进先出(FIFO)的方式获得信号量。如果fairness为false,则不保证这种顺序。

2. 示范代码

下面这段代码演示了某种资源只限于5个线程访问:
package com.clzhang.sample.thread;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SyncSemaphore {
    private static final SimpleDateFormat MY_SDF = new SimpleDateFormat("mm:ss");

    // 只能5个线程同时访问
    private final Semaphore available = new Semaphore(5);

    class Mythread implements Runnable {
        @Override
        public void run() {
            try {
                // 获取许可
                available.acquire();

                // 业务处理
                Thread.sleep((long) (Math.random() * 10000));
                System.out.println("[" + MY_SDF.format(new Date()) + "]"
                        + Thread.currentThread().getName() + " ending process!");

                // 访问完后,释放
                available.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        // 创建线程池
        ExecutorService executorPool = Executors.newCachedThreadPool();

        // 加入线程
        SyncSemaphore ins = new SyncSemaphore();
        for (int index = 0; index < 10; index++) {
            executorPool.execute(ins.new Mythread());
        }

        // 关闭线程池
        executorPool.shutdown();
    }
}

输出
[43:04]pool-1-thread-5 ending process!
[43:04]pool-1-thread-7 ending process!
[43:08]pool-1-thread-9 ending process!
[43:11]pool-1-thread-3 ending process!
[43:11]pool-1-thread-4 ending process!
[43:13]pool-1-thread-1 ending process!
[43:13]pool-1-thread-2 ending process!
[43:14]pool-1-thread-6 ending process!
[43:16]pool-1-thread-10 ending process!
[43:21]pool-1-thread-8 ending process!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值