1 package com.example.demo02.thread;
2
3 import java.util.Random;
4 import java.util.concurrent.Semaphore;
5
6 class Parent implements Runnable {
7 private String name;
8
9 /**
10 * Semaphore是一种基于计数的信号量。它可以设定一个阈值,基于此,多个线程竞争获取许可信号,做自己的申请后归还,超过阈值后,线程申请许可信号将会被阻塞。Semaphore可以用来构建一些对象池,资源池之类的,比如数据库连接池,我们也可以创建计数为1的Semaphore,将其作为一种类似互斥锁的机制,这也叫二元信号量,表示两种互斥状态。它的用法如下:
11 * availablePermits函数用来获取当前可用的资源数量
12 * wc.acquire(); //申请资源
13 * wc.release();// 释放资源
14 */
15 private Semaphore semaphoreSit;
16
17 public Parent(String name, Semaphore semaphoreSit) {
18 this.name = name;
19 this.semaphoreSit = semaphoreSit;
20 }
21
22 @Override
23 public void run() {
24 int count = semaphoreSit.availablePermits();
25 if (count > 0) {
26 System.out.println(name + "天助我也,终于有座位了...");
27 } else {
28 System.out.println(name + "怎么没有座位了...");
29 }
30 try {
31 semaphoreSit.acquire();
32 System.out.println(name + "终于轮我上厕所了..爽啊");
33 Thread.sleep(new Random().nextInt(1000)); // 模拟上厕所时间。
34 System.out.println(name + "厕所上完了...");
35 } catch (InterruptedException e) {
36 e.printStackTrace();
37 } finally {
38 semaphoreSit.release();
39 }
40 }
41 }
42
43 public class ThreadDemo6 {
44 public static void main(String[] args) {
45 Semaphore semaphore = new Semaphore(3);
46 for (int i = 1; i <= 10; i++) {
47 Parent parent = new Parent("第" + i + "个人,", semaphore);
48 new Thread(parent).start();
49 }
50
51 }
52 }