```java
public class SemaphoreTest {
/**
* 初始化信号量
*/
static int count;
static final Semaphore s = new Semaphore(1);
/**
* 用信号量保证互斥
*/
static void addOne() throws InterruptedException {
s.acquire();
try {
count++;
System.out.println(SemaphoreTest.count);
} finally {
s.release();
}
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(() -> {
try {
SemaphoreTest.addOne();
// 最开始我是放在这打印的,但是发现有重复的值,起初怀疑 addOne() 方法不是线程安全的,后来将打印发到 addOne() 方法里面就正常显示了
// TODO
// System.out.println(SemaphoreTest.count);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
// 打印的值不是预期的 10,因为子线程还没有执行完,主线程就执行完了
System.err.println(SemaphoreTest.count);
}
}
**请问为什么加在 SemaphoreTest.addOne(); 代码后面,打印count,会出现重复出现的情况**
```java
2
2
3
6
5
4
8
7
9
10
Process finished with exit code 0