2010-02-21 72 views
4

我有兩個線程,我想確保我正在LinkedBlockingQueue上正確地進行同步。這是正確的嗎?或者是(messageToCommsQueue)上的顯式同步不是必需的?這是否需要顯式同步?

聲明:

private LinkedBlockingQueue<BaseMessage> messagesToCommsQueue; 

方法一:

private void startOperationModeStatusMessageExecutor() { 

    ScheduledExecutorService operationModeStatusExecutor = Executors.newSingleThreadScheduledExecutor(); 
    operationModeStatusExecutor.scheduleAtFixedRate((new Runnable() { 

     @Override 
     public void run() { 
      MT02OperationModeStatusMessage commsOperateMsg; 
       commsOperateMsg = MessageFactory.getMT1102OperationModeStatusMessage(status.ordinal()); 
      synchronized (messagesToCommsQueue) { 
       messagesToCommsQueue.add(commsOperateMsg); 
      } 
     } 

    }), 0, 10, TimeUnit.SECONDS); 
} 

方法二:

Executor commsSenderExecutor = Executors.newSingleThreadExecutor(); 
    commsSenderExecutor.execute(new Runnable() { 

     @Override 
     public void run() { 
      while (getStatus().equals(OperationModeStatus.INITIATE) || getStatus().equals(OperationModeStatus.OPERATE)) { 
       BaseMessage m = null; 
       try { 
        synchronized (messagesToCommsQueue) { 
         m = messagesToCommsQueue.take(); 
        } 
       } catch (InterruptedException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 



      } 
     } 

    }); 

回答

3

是的,這是沒有必要的。 JavaDoc說:

BlockingQueue實現是線程安全的。

相關問題