这是否需要显式同步?
我有两个线程,我想确保我在 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();
}
}
}
});
I have two threads, and I want to make sure I am doing the synchronization correctly on the LinkedBlockingQueue.. Is this correct? Or is the explicit synchronization on (messageToCommsQueue) not necessary?
Declaration:
private LinkedBlockingQueue<BaseMessage> messagesToCommsQueue;
Method one:
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);
}
Method Two:
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();
}
}
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,没有必要。 JavaDoc 说:
Yes, it's not necessary. JavaDoc says that: