首页 > 其他 > 详细

Semaphore

时间:2020-03-17 22:26:35      阅读:43      评论:0      收藏:0      [点我收藏+]

信号量主要用于两个目的:

1.用于多个共享资源的互斥使用

2.用于并发数的控制.

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i <= 6; i++) {
            new Thread(() -> {

                System.out.println(Thread.currentThread().getName() + "\t 抢到车位");
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName());
                    try {
                        TimeUnit.SECONDS.sleep(3);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "\t 停车三秒后离开车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }
            }, String.valueOf(i)).start();
        }
    }
}

  

Semaphore

原文:https://www.cnblogs.com/sunliyuan/p/12513858.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!