gpt4 book ai didi

java - 这需要显式同步吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:29:06 24 4
gpt4 key购买 nike

我有两个线程,我想确保我在 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();
}



}
}

});

最佳答案

是的,没有必要。 JavaDoc说:

BlockingQueue implementations are thread-safe.

关于java - 这需要显式同步吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2307697/

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