【发布时间】:2016-01-22 22:04:12
【问题描述】:
我尝试在我的PQueue 中设置Maximum Waiting Time。这个Maximum Waiting Time 将自动检查我的PQueue,如果有任何links 等待超过Maximum Waiting Time 来删除它。我对正在运行的代码进行了此更改,但在删除链接后它完全停止了。我想根据等待时间条件从我的PQueue 中删除所有元素。你能告诉我我在这里缺少什么吗?
这是我的课:
public class MyClass {
public static PriorityQueue <LinkNodeLight> PQueue = new PriorityQueue <> ();
private static Set<String> DuplicationLinksHub = new LinkedHashSet <> ();
private static Integer IntraLinkCount = new Integer (0);
private static Integer InterLinkCount = new Integer (0);
private static Integer DuplicationLinksCount = new Integer (0);
private static Integer MaxWaitTime = new Integer (60000); // 1 M= 60000 MS
@SuppressWarnings("null")
LinkNode deque(){
LinkNode link = null;
synchronized (PQueue) {
link = (LinkNode) PQueue.poll();
if (link != null) {
link.setDequeTime(new DateTime());
if (link.isInterLinks())
synchronized (InterLinkCount) {
InterLinkCount--;
}
else
synchronized (IntraLinkCount) {
IntraLinkCount--;
}
}
synchronized (PQueue) {
if (link.waitingInQueue()>MaxWaitTime) {
link = (LinkNode) PQueue.remove();
System.out.println("*********************************");
System.out.println("This Link is Deopped: " + link);
System.out.println("%%% MaX Waiting Time:" + (MaxWaitTime/60000)+"Min");
System.out.println("*********************************");
}
}
return link;
}
【问题讨论】:
-
尚未查看您的所有代码,但在
InterLinkCount或IntraLinkCount上同步不起作用。您不断更改这些变量引用的对象,因此不同的线程不会获取相同的锁。 -
@user2357112 这不是我的整个项目,因为它是一个大程序。这是其中的一部分。如果需要,我可以提供有关代码的其他程序
-
一般性评论:不要使用
new Integer(n),而是使用Integer.valueOf(n)。效率更高。 -
永远不要在可变变量上同步!
synchronized(IntraLinkCount){IntraLinkCount--;}不是线程安全的! -
@Holger 那你更喜欢用什么来代替 synchronized(IntraLinkCount){IntraLinkCount--;} 我应该怎么用呢?
标签: java search priority-queue