我编写了一个多线程程序,其中我看到了一些奇怪的行为。下面是代码。
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
}
问题陈述:-
我刚刚注意到的一件奇怪的事情是 - 在下面的 else if 循环中,如果您在 run 方法中看到我上面的代码,if the command.getDataCriteria() is Previous
那么它也会进入 else if 块(这是 for New
),这不应该像我一样发生做.equals
检查?为什么会这样?
else if(command.getDataCriteria().equals(PDSLnPConstants.DATA_CRITERIA_NEW)) {
更新:-
下面是来自我的控制台的图像。
你可以清楚地看到,dataCriteria was New
它去了PREVIOUS block