gpt4 book ai didi

java - TimerTask 同步失败

转载 作者:行者123 更新时间:2023-12-02 02:36:37 25 4
gpt4 key购买 nike

我正在开发一个 ODL 应用程序,并从我的主函数中安排了一个任务 ( MonitorLinksTask ),以便监视拓扑的所有链接中的延迟。 我想为每个链接发送一个数据包,并在 Controller 收到该数据包后,为下一个链接发送下一个数据包。 main 中的代码是:

Timer time = new Timer();
MonitorLinksTask monitorLinksTask = new MonitorLinksTask();
time.schedule(monitorLinksTask, 0, 5000);

MonitorLinksTask是:

public class MonitorLinksTask extends TimerTask{

static boolean flag = false;

public void run() {

for (DomainLink link : linkList) {
sendPacket();
while (flag == false){
//waits until it gets notified that the sent packet has been received
}
System.out.println("Sending next packet.");
System.out.println("----------");
flag = false;
}

}
}

哪里:

private void sendPacket(){
Packet packet;
PacketProcessingService packetProcessingService = ... ;
// .... fill the packet ....
System.out.println("Packet transmitted at time " + System.currentTimeMillis());
packetProcessingService.transmitPacket(packet);
}

所以到目前为止,任务每 5 秒运行一次,并调用函数为每个链路发送一个数据包,以计算图中每个链路的单程延迟。

我创建了一个监听器,以便 Controller 每次收到数据包时,都会通知 MonitorLinksTask它收到了数据包,然后 MonitorLinksTask可以发送下一张。

public void onPacketReceived(PacketReceived packetReceived) {

System.out.println("Packet received at time " + System.currentTimeMillis());
MonitorLinksTask.flag = true;

}

但是,我的程序在 MonitorLinksTask 的前两次执行中工作正常。第三个停止了。具有两个链接的情况的示例输出:

Packet transmitted at time 1549333576093
Packet received at time 1549333576096
Sending next packet.
Packet transmitted at time 1549333576111
Packet received at time 1549333576115
Sending next packet.
----------
Packet transmitted at time 1549333576122
Packet received at time 1549333576124
Sending next packet.
Packet transmitted at time 1549333576128
Packet received at time 1549333576129
Sending next packet.
----------
Packet transmitted at time 1549333576136
Packet received at time 1549333576140

有什么想法吗?

最佳答案

假设所有这些都发生在同一个 JVM 中:

  1. Thread.currentThread().getName() 添加到您的日志中,以便从日志中清楚地了解执行是多线程还是单线程;
  2. 如果是前者,请尝试向 flag 添加 volatile 修饰符。

由于上述内容有助于解决您的问题,很明显,这是由于线程(TimerTask 线程和您的应用线程)之间缺乏可见性更新造成的。让我建议Oracle Concurrency加深您对 Java 多线程的了解。提到了您的具体问题here .

关于java - TimerTask 同步失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46213145/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com