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