我正在通过暂停执行相同的事情来等待其中一个完成的线程来改进我的并发程序。但是,它不能正确唤醒线程。这是代码。为什么我的通知方法无法正常工作?
//to store graphs, if a thread finds the graph it is going to compute is in the entry, it waits, otherwise it compute then notify all other threads waiting on it.
Map<Graph, Object> entry = new ConcurrentHashMap<Graph, Object>();
public Result recursiveMethod(Graph g) {
if (entry.get(g) != null) {//if the graph is in the entry, waits
synchronized(entry.get(g)) {
entry.get(g).wait();
}
//wakes up, and directly return the result
return result;
}
synchronized(entry) {
if (entry.get(g) == null)//if the graph is not in the entry, continue to compute
entry.put(g,new Object());
}
//compute the graph recursively calls this method itself...
calculate here...
//wake up threads waiting on it, and remove the graph from entry
synchronized(entry.get(g)){
entry.get(g).notifyAll();
}
entry.remove(g);
return result;
}
这个方法被许多线程调用。在线程开始计算之前,它会查找条目以查看是否有另一个线程计算相同的图形。如果是这样,它等待。 如果不是,则继续计算。在计算出结果后,它会通知所有正在等待的线程。
我使用地图来配对图形和对象。该对象是锁。 请注意,该地图可以识别两个相同的图形,即以下代码返回true。
Graph g = new Graph();
entry.put(g, new Object());
Graph copy = new Graph(g);
entry.get(g) == entry.get(copy) //this is true
因此,entry.get(g)应该可以是锁/监视器。 但是,大多数线程并没有被唤醒,只有3-4线程。 当等待的线程数等于我的计算机可以创建的线程数时,这意味着所有的线程都在等待,这个程序永远不会终止。
为什么没有entry.get(g).notifyAll()工作?
我无法理解代码,也许是因为您没有包含所有代码。您是否注意到“if(entry.get(g)!= null)”将始终返回true,因为您刚插入条目。因此,你会一直等待。 – JimN 2012-07-27 02:00:51
除非我提供的代码没有问题,否则不需要查看所有其他代码。谢谢你的回答,我发现当我在这里重写它时,我只是把if语句写错了,我改变了它。问题依然存在。 – user1556378 2012-07-27 02:48:00
@ user1556378问题是你的代码充满了问题,没有任何意义。线程是如何产生的?什么是“结果”?你想达到什么目的?我已经读了3次你的代码,但仍然无法理解它。 – 2012-07-27 04:35:28