美文网首页
semaphore信号量使用

semaphore信号量使用

作者: 不知不怪 | 来源:发表于2019-01-21 15:32 被阅读0次
    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

    相关文章

      网友评论

          本文标题:semaphore信号量使用

          本文链接:https://www.haomeiwen.com/subject/qimcjqtx.html