【发布时间】:2011-12-02 17:35:20
【问题描述】:
我不明白这段代码有什么问题。有时两个线程开始执行 try 块。每次调用该函数时,我都会创建一个 popo 的新实例。有没有大佬可以看看是什么问题?
public class Instance {
private static AtomicInteger i = new AtomicInteger(0);
public synchronized void incrementInstance() {
i.getAndIncrement();
}
public synchronized void decrementInstance() {
i.getAndDecrement();
}
public synchronized int getInstances() {
return i.get();
}
}
public class popo {
private static volatile MyMutex instanceMutex = new MyMutex();
public void doSomething() {
synchronized (instanceMutex) {
final Instance no = new Instance();
if (no.getInstances() > 0) {
instanceMutex.wait();
} else {
no.incrementInstance();
}
}
try {
// do something
} finally {
synchronized (instanceMutex) {
final Instance no = new Instance();
if (no.Instances() > 0) {
no.decrementInstance();
}
instanceMutex.notify();
}
}
}
private static class MyMutex {}
}
【问题讨论】:
标签: java multithreading thread-safety mutex synchronized