我开了 100 个线程用同一个 id 分别去请求这两个方法,把这 100 次方法执行时间的平均值取出来,并且相同的方法重复做了三次得到结果: a: 24907.9ms, b: 24831.1ms ,看结果方法 b 好一点,但这个差距是不是很小啊?
@Controller
@RequestMapping("/bench/")
public class BenchController {
private static Object[] lockObj;
private static AtomicReference<Integer>[] locks;
static {
lockObj = new Object[100];
for (int i = 0; i < lockObj.length; i++) {
lockObj[i] = new Object();
}
locks = new AtomicReference[100];
for (int i = 0; i < locks.length; i++) {
locks[i] = new AtomicReference<Integer>(null);
}
}
@RequestMapping("a")
@ResponseBody
public long a(int id) throws Exception {
long start = System.currentTimeMillis();
int index = id % 100;
synchronized (lockObj[index]) {
Thread.sleep(500);
}
long result=System.currentTimeMillis() - start;
System.out.println(result);
return result;
}
@RequestMapping("b")
@ResponseBody
public long b(int id) throws Exception {
long start = System.currentTimeMillis();
int index = id % 100;
while (!locks[index].compareAndSet(null, id)) {
}
Thread.sleep(500);
locks[index].compareAndSet(id, null);
long result=System.currentTimeMillis() - start;
System.out.println(result);
return result;
}
}