cache3
来源:13-4 用ConcurrentHashMap保证并发安全

慕九州8243454
2022-02-20
为什么我运行第三种的时候一直是132的结果呢。我甚至都搞了第二个线程之后休眠了(让第三个线程暂缓创建),同时我还有一个问题,compute的时候不是sync修饰了吗,为什么还会出现连续两句话的“进入缓存机制”,sleep不是不会释放锁资源吗
相关截图:
相关截图:
写回答
2回答
-
Murano_Satomi
2022-06-24
为什么线程执行是132,你试试看 在线程 3 创建前 主线程 睡眠久点
2.为什么还会出现连续两句话的“进入缓存机制”
因为 synchronized 修饰的方法 的 “进入缓存机制”和 线程执行后 打印的 "第一次的计算结果:" 不在同一个 synchronized 方法内
然后下一个线程2 进入 compute(676) 比 线程1 System.out.println("第二次的计算结果:"+result); 要快
只要 把 输出语句 都放进 synchronized 既可
代码
imooccacheimooccache.computable.Computableimooccache.computable.ExpensiveFunctionjava.util.HashMapjava.util.MapImoocCache3<> Computable<> { Map<> = HashMap()Computable<> (Computable<> c) { .= c} (arg) Exception { System..println()result = .get(arg)(result == ) { result = .compute(arg).put(argresult)} System..println(Thread.().getName()++result)result} (String[] args) Exception { ImoocCache3<StringInteger> expensiveComputer = ImoocCache3<>( ExpensiveFunction())Thread(Runnable() { () { { Integer result = .compute()} (Exception e) { e.printStackTrace()} } }).start()Thread(Runnable() { () { { Integer result = .compute()} (Exception e) { e.printStackTrace()} } }).start()Thread.()Thread(Runnable() { () { { Integer result = .compute()} (Exception e) { e.printStackTrace()} } }).start()} }
00 -
悟空
2022-02-21
这是我的代码,你看一下:
imooccache; imooccache.computable.Computable; imooccache.computable.ExpensiveFunction; java.util.HashMap; java.util.Map; ImoocCache3<,> Computable<,> { Map<, > = HashMap(); Computable<,> ; ImoocCache3(Computable<, > c) { .= c; } compute(arg) Exception { System..println(); result = .get(arg); (result == ) { result = .compute(arg); .put(arg, result); } result; } main(String[] args) Exception { ImoocCache3<String, Integer> expensiveComputer = ImoocCache3<>( ExpensiveFunction()); Thread(Runnable() { run() { { Integer result = .compute(); System..println(+result); } (Exception e) { e.printStackTrace(); } } }).start(); Thread(Runnable() { run() { { Integer result = .compute(); System..println(+result); } (Exception e) { e.printStackTrace(); } } }).start(); Thread(Runnable() { run() { { Integer result = .compute(); System..println(+result); } (Exception e) { e.printStackTrace(); } } }).start(); } }
如果还有问题,可以贴一下你的代码,上面你拍的照片我没办法转成代码,很难排查。
042024-01-15