0

我编写了一个多线程程序,其中我看到了一些奇怪的行为。下面是代码。

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

4

1 回答 1

1

如果你的代码真的

if(command.getDataCriteria().equals(PDSLnPConstants.DATA_CRITERIA_PREVIOUS)) {
   ...
else if(command.getDataCriteria().equals(PDSLnPConstants.DATA_CRITERIA_NEW)) {
   ...
}

那么两个...s 都不可能被执行。它不依赖于同步、线程、错误的 equals 实现或其他任何东西。还有一些你不理解的东西(这两者中的 run() 调用真的是一样的吗?),或者可能是我对你的问题陈述不理解的东西(这很令人困惑)。

于 2012-08-18T23:25:54.290 回答