Semaphore

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

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

2.用于并发数的控制.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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();
        }
    }
}

  

posted @   石shi  阅读(149)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示