【学习笔记】Java-Concurrent-Semaphore

同时只有一个人可以吃面包的示例

    /**
     * 第一个线程 与第二个同时执行
     */
    public static void firstThread0(Context context) throws Exception{
        while(true) {
            eatBread(context);
            Thread.sleep(1000); //每吃一个面包休息一秒
        }
    }

    /**
     * 第二个线程
     */
    public static void secondThread0(Context context) throws Exception{
        while(true) {
            eatBread(context);
            Thread.sleep(1000);
        }
    }

    public static void eatBread(Context context) throws Exception {
        //请求分配一个面包
        context.breadDispatcher.acquire(1);
        log("我吃了一个面包");
        //把座位还回去
        context.breadDispatcher.release();
    }

    public static void log(String args){
        System.out.println(Thread.currentThread().getName() + "\t" + new Date() + "\t" + args);
    }

    public static class Context {
        //这里使用一个遵守FIFO规则的Semaphore
        //来看看cpu时间片的分配算法会让谁先吃到第一个面包
        public Semaphore breadDispatcher = new Semaphore(1, true);

        public Context() {

        }
    }

运行结果:

Thread-1    Mon Nov 05 15:46:08 CST 2018    我吃了一个面包
Thread-0    Mon Nov 05 15:46:08 CST 2018    我吃了一个面包
Thread-1    Mon Nov 05 15:46:09 CST 2018    我吃了一个面包
Thread-0    Mon Nov 05 15:46:09 CST 2018    我吃了一个面包

用途:

1.为容器设置边界

2.设置同时执行某个操作的最大线程数量

常用函数

//if(还有许可证) 取走许可证 else 阻塞等待可用许可证

public void acquire() throws InterruptedException

//归还一个许可证

public void release()

猜你喜欢

转载自blog.csdn.net/qq_34622036/article/details/83750455
今日推荐