Java

Semaphore用法

2019-08-19  本文已影响11人  endlesswork

共享锁,支持公平锁,可以指定锁的数量。

public class SemaphoreDemo  implements Runnable{
    public static Semaphore semaphore = new Semaphore(10);

    public String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public SemaphoreDemo(String name){
        this.name = name;
    }

    @Override
    public void run() {
        try {
            System.out.println(name + "开始:" +getDate());
            semaphore.acquire();
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            semaphore.release();
            System.out.println(name + "结束:" +getDate());
        }
    }

    public static String getDate(){
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        return  dateFormat.format(date);
    }


    public static void  main(String []args){
        //因为要控制5个线程 采用线程池模拟
        ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
        for (int i = 0;i<20;i++){
            threadPoolExecutor.execute(new SemaphoreDemo("task"+i));
        }
    }
}

结果如下

task0开始:2019-04-14 :04:02:24
task3开始:2019-04-14 :04:02:24
task2开始:2019-04-14 :04:02:24
task1开始:2019-04-14 :04:02:24
task4开始:2019-04-14 :04:02:24
task3结束:2019-04-14 :04:02:29
task4结束:2019-04-14 :04:02:29
task1结束:2019-04-14 :04:02:29
task0结束:2019-04-14 :04:02:29
task2结束:2019-04-14 :04:02:29
task6开始:2019-04-14 :04:02:29
task5开始:2019-04-14 :04:02:29
task8开始:2019-04-14 :04:02:29
task7开始:2019-04-14 :04:02:29
task9开始:2019-04-14 :04:02:29
task6结束:2019-04-14 :04:02:34
task10开始:2019-04-14 :04:02:34
task5结束:2019-04-14 :04:02:34
task7结束:2019-04-14 :04:02:34
task8结束:2019-04-14 :04:02:34
task9结束:2019-04-14 :04:02:34
task11开始:2019-04-14 :04:02:34
task13开始:2019-04-14 :04:02:34
task12开始:2019-04-14 :04:02:34
task14开始:2019-04-14 :04:02:34
task10结束:2019-04-14 :04:02:39
task11结束:2019-04-14 :04:02:39
task15开始:2019-04-14 :04:02:39
task16开始:2019-04-14 :04:02:39
task12结束:2019-04-14 :04:02:39
task13结束:2019-04-14 :04:02:39
task14结束:2019-04-14 :04:02:39
task18开始:2019-04-14 :04:02:39
task19开始:2019-04-14 :04:02:39
task17开始:2019-04-14 :04:02:39
task15结束:2019-04-14 :04:02:44
task16结束:2019-04-14 :04:02:44
task19结束:2019-04-14 :04:02:44
task18结束:2019-04-14 :04:02:44
task17结束:2019-04-14 :04:02:44

上一篇 下一篇

猜你喜欢

热点阅读