zoukankan      html  css  js  c++  java
  • 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!

  • 相关阅读:
    python3文件操作
    python3复习
    python3集合
    python购物车
    python小知识点总结
    python-review01
    python字典
    04day->python列表和元祖
    python字符串操作
    《令人拍案称奇的Mask RCNN》
  • 原文地址:https://www.cnblogs.com/nayitian/p/3317250.html
Copyright © 2011-2022 走看看