# 问题复现
for (int i = 0; i < 100; i++) {
new Thread(new OrderService()).start();
}
public class OrderService implements Runnable {
private OrderNumGenerator orderNumGenerator = new OrderNumGenerator();
// private Lock lock = new ReentrantLock();
private Lock lock = new ZkLock();
@Override
public void run() {
getNumber();
}
private void getNumber() {
try {
lock.getLock();
// lock.lock();
String number = orderNumGenerator.getNumber();
System.out.println(Thread.currentThread().getName() + ",获取的number:" + number);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}
}
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
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
输出
这里线程的名字已经超过100了,按理来说最大应该是100才对?
# 解决
以下是thread的源码
private static int threadInitNumber;
private static synchronized int nextThreadNum() {
return threadInitNumber++;
}
1
2
3
4
2
3
4
因为OrderService类也继承了Runnable接口,所以这个threadInitNumber变量被初始化了两次。😅