这需要显式同步吗?

时间:2010-02-21 22:25:22

标签: java multithreading thread-safety executor

我有两个线程,我想确保我在LinkedBlockingQueue上正确进行同步..这是正确的吗?或者是否必须在(messageToCommsQueue)上进行显式同步?

声明:

    private LinkedBlockingQueue<BaseMessage> messagesToCommsQueue;

方法一:

private void startOperationModeStatusMessageExecutor() {

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

        @Override
        public void run() {
            ModeStatusMessage commsOperateMsg;
                commsOperateMsg = MessageFactory.getModeStatusMessage(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(ModeStatus.INITIATE) || getStatus().equals(ModeStatus.OPERATE)) {
                BaseMessage m = null;
                try {
                    synchronized (messagesToCommsQueue) {
                        m = messagesToCommsQueue.take();
                    }
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }



            }
        }

    });

1 个答案:

答案 0 :(得分:4)

是的,没有必要。 JavaDoc说:

  

BlockingQueue实现是线程安全的。