题解:
1.
public void handle(int threadNum) throws InterruptedException {
int localCurrent = 0;
while (true) {
synchronized (this) {
if (current < max) {
current++;
localCurrent = current;
break;
}
}
}
this.doHandle(threadNum, localCurrent);
synchronized (this) {
current--;
}
}
2.
3.
学到的知识:题外可以用semphore、fixthreadpool或者设置全局变量等等解决
一些锁粗化和细化的东西:1.在while里面写synchronized,而不是在synchronized里面写while。2.doHandle的调用不需要写在synchronized里面
错误题解
导致的问题:死锁 你这个问题就出在在synchronized里面while,你先锁了this,然后才循环判断curr,然而如果此时已经达到max,你就永远锁在里面出不来了,主要是因为和notify公用锁了。
object里面也没有lock方法。
著作权归NoLongerConfused所有。商业转载请联系NoLongerConfused获得授权,非商业转载请注明出处。