Platform.runLater

时间:2013-09-05 17:02:12

标签: java javafx observablelist

我有和app连接到套接字连接,并且连接向我发送了很多信息..让我说每秒300个订单(可能更多)..我有一个类(它就像一个监听器,对...做出反应)一些事件和那个事件有接收该命令的命令...创建一个对象,然后将它添加到一个ObservableList(这是一个tableView的源)..这样我的GUI显示该顺序。但是这里出现了问题,如果observableList上已经存在这个顺序..我无法添加它..我必须更新它(我做)..但有些时候..有些订单这个条件不起作用并再次添加订单。

我会告诉你它是如何使用某些代码的。

 public class ReceivedOrderListener 
 {
     ev = Event; //Supose that this is the event with the order
     if(!Repository.ordersIdMap.containsKey(ev.orderID))
     {    

         Platform.runLater(new Runnable() 
         {
            @Override public void run() 
            {                                                                    
                Repository.ordersCollection.add(ev.orderVo);                        
            }
         } 
      });
      Repository.ordersIdMap.put(ev.orderID, ev.orderVo);
  }

现在好了..这是我的代码的简历。 ev是我的事件,包含订单的所有信息,orderID是我用来查看订单是否已存在的密钥(并且是唯一的)。 “Repository”是一个单例类,“ordersCollection”是一个ObservableList,“ordersIdMap”是一个HashMap

1 个答案:

答案 0 :(得分:1)

如果ReceivedOrderListener由多个线程执行,那么它看起来像是“check-then-act”竞争条件。

-> ORDER1 comes to the listener
T1 checks ordersIdMap.containsKey(ORDER1) it returs false
T1 proceeds to do Platform.runLater to add the order
-> ORDER1 comes to the listener again
-> T2 checks ordersIdMap.containsKey(ORDER1) it returs false again
now T1 proceeds to do ordersIdMap.put(ORDER1)
-> T2 proceeds to do Platform.runLater to add the order again