Semaphore(三)

Semaphore(三)

了解Semaphore - 实例了解

实例演示

通过前面的粗略的分析,可能还是一头污水,Talk is cheap,show your code

情景

饭堂打饭窗口总共就10个,此时有20个同学一听到下课铃声,就冲去饭堂打饭。假设他们都穿了一样的AJ球鞋,腿一样长,身高一样高,都是1米7,而且出发地点都是教室的最后排。那么他们怎么样才能在10个打饭窗口都搭得了饭呢。

代码

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
29
30
31
32
33
34
35
public class TestSemaphore {
static class Student implements Runnable {
private int n;
private Semaphore semaphore;

public Student(int n, Semaphore semaphore) {
this.n = n;
this.semaphore = semaphore;
}

@Override
public void run() {
try {
semaphore.acquire();
System.out.println("同学 " + n + " : 正在打饭");
Thread.sleep(2000);
System.out.println("同学 " + n + " : 打饭完了");
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {
int student = 20;
int window = 10;
Semaphore semaphore = new Semaphore(window);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < student; i++) {
executorService.execute(new Student(i + 1, semaphore));
}
executorService.shutdown();
}
}

结果

Semaphore实例结果

可以看到一开始同学1 - 10都在打饭,此时打饭窗口满了,过了一会,同学1打饭完了,此时11号顶上…其他情况以此类推。

Semaphore小结

Semaphore适用于限制访问资源的线程数目的情景。映射到现实生活的例子就如同打饭窗口,银行办证窗口等需要排队去获取限定资源的情况。

-------------本文结束感谢您的阅读-------------