我写了一个多线程程序,其中我看到了一些奇怪的行为。以下是代码。
class Task implements Runnable {
private Command command;
private BlockingQueue<Integer> existPool;
private BlockingQueue<Integer> newPool;
private int existId;
private int newId;
public Task(Command command, BlockingQueue<Integer> pool1, BlockingQueue<Integer> pool2) {
this.command = command;
this.existPool = pool1;
this.newPool = pool2;
}
public void run() {
if(command.getDataCriteria().equals(PDSLnPConstants.DATA_CRITERIA_PREVIOUS)) {
try {
// Getting existing id from the pool
existId = existPool.take();
attributeGetSetMethod(existId);
} catch (Exception e) {
getLogger().log(LogLevel.ERROR, e.getLocalizedMessage());
} finally {
// And releasing that existing ID for re-use
existPool.offer(existId);
}
}
//Something wrong happening here
else if(command.getDataCriteria().equals(PDSLnPConstants.DATA_CRITERIA_NEW)) {
try {
// Getting new id from the pool
newId = newPool.take();
attributeGetSetMethod(newId);
} catch (Exception e) {
getLogger().log(LogLevel.ERROR, e.getLocalizedMessage());
} finally {
// And releasing that new ID for re-use
newPool.offer(newId);
}
}
}
}
从下面的代码中。以上运行方法正在调用。
for (int i = startRange; i <= endRange; i++) {
availableExistingIds.add(i);
}
for (int n = newStartRange; n <= newEndRange; n++) {
availableNewIds.add(n);
}
BlockingQueue<Integer> existIdPool = new ArrayBlockingQueue<Integer>(11, false, availableExistingIds);
BlockingQueue<Integer> newIdPool = new ArrayBlockingQueue<Integer>(21, false, availableNewIds);
GUID_ID_MAPPING = new LinkedHashMap<Integer, LinkedHashMap<Integer, String>>();
long startTime = System.currentTimeMillis();
long endTime = startTime + (durationOfRun*60*1000L);
// Running for particular duration of time
while(System.currentTimeMillis() <= endTime) {
Command nextCommand = getNextCommandToExecute();
Task nextCommandExecutorRunnable = new Task(nextCommand, existIdPool, newIdPool);
executorService.submit(nextCommandExecutorRunnable); // Submit it for execution
}
问题陈述: -
我刚才注意到的一个奇怪的事情是 - 在下面的if if循环中,如果你在run方法if the command.getDataCriteria() is Previous
中看到我的上面的代码,那么它也会被输入else if块(用于{{1当我正在进行New
检查时,哪个不应该正常发生?为什么会这样?
.equals
更新: -
以下是我的控制台中的图片。
您可以清楚地看到else if(command.getDataCriteria().equals(PDSLnPConstants.DATA_CRITERIA_NEW)) {
,然后转到dataCriteria was New
答案 0 :(得分:1)
如果您的代码真的是
if(command.getDataCriteria().equals(PDSLnPConstants.DATA_CRITERIA_PREVIOUS)) {
...
else if(command.getDataCriteria().equals(PDSLnPConstants.DATA_CRITERIA_NEW)) {
...
}
然后两个...
都不可能被执行。它不依赖于同步,线程,错误的等于实现或其他任何东西。还有一些你不理解的东西(它是否真的与两者中的run()调用相同?),或者可能是我对你的问题陈述无法理解的东西(这很令人困惑)。