semaphore信号量使用

package com.battcn;

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 SemaphoreDemo {
    private static Semaphore smp = new Semaphore(3);
    // 注意我创建的线程池类型,
    private static ExecutorService se = Executors.newCachedThreadPool();
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss SSS");

    public static void run(String id) {
        try {
            smp.acquire();
            System.out.println(simpleDateFormat.format(new Date()) + " Thread " + id + " is working");
            Thread.sleep(1000);
            smp.release();
            System.out.println(simpleDateFormat.format(new Date()) + " Thread " + id + " is over");
        } catch (InterruptedException e) {
        }
    }

    public static void main(String[] args) {
        String ayy[] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };
        for (String string : ayy) {
            se.submit(() -> SemaphoreDemo.run(string));
        }
        se.shutdown();
    }
}

15:25:42 131 Thread a is working
15:25:42 131 Thread c is working
15:25:42 131 Thread b is working
15:25:43 132 Thread c is over
15:25:43 132 Thread e is working
15:25:43 132 Thread f is working
15:25:43 132 Thread d is working
15:25:43 132 Thread b is over
15:25:43 132 Thread a is over
15:25:44 132 Thread g is working
15:25:44 132 Thread f is over
15:25:44 132 Thread e is over
15:25:44 132 Thread d is over
15:25:44 132 Thread h is working
15:25:44 132 Thread i is working
15:25:45 132 Thread j is working
15:25:45 132 Thread g is over
15:25:45 132 Thread h is over
15:25:45 133 Thread i is over
15:25:46 133 Thread j is over

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容