Java 取消()方法

Java 取消()方法,java,multithreading,Java,Multithreading,我有一个下面的可运行任务,它是通过使用ThreadPoolExecutor ThreadPoolExecutor=new ThreadPoolExecutor(1,1,0L,TimeUnit.ms,new ArrayBlockingQueue(1))运行的这确保队列中只有一个等待的任务 protected void waitAndSweep(final String symbol) { try { runnable = new Runnable() {

我有一个下面的可运行任务,它是通过使用
ThreadPoolExecutor ThreadPoolExecutor=new ThreadPoolExecutor(1,1,0L,TimeUnit.ms,new ArrayBlockingQueue(1))运行的这确保队列中只有一个等待的任务

protected void waitAndSweep(final String symbol) {
    try { 

        runnable = new Runnable() {
          @Override
          public void run() {
            try {
             // long sweepTime = symbolInfo.getSweepTime(symbol);
              // long timeSinceLastSweep = System.currentTimeMillis() - lastSliceSentTime;
              boolean sliceDone = Quant.equals(wave.getCommitedQuantity() % getSliceQuantity(),0);
              if(sliceDone){
                long timeSinceLastSliceQtySent = lastSliceSentTime == 0 ? getInterval() : System.currentTimeMillis() - lastSliceSentTime;
                long waitTime = timeSinceLastSliceQtySent >= getInterval() ? 0 : getInterval() - timeSinceLastSliceQtySent;
                logTradeEvent("waitAndSweep", symbol, "waittime: " + waitTime);
                if (waitTime > 0){
                  Thread.sleep(waitTime);
                }
              }

              callSweep(symbol);
            } catch(InterruptedException ie){
              ie.printStackTrace();
            }
            catch (Exception e) {
              logEvent(StrategyEntry.ERROR, "waitAndSweep", symbol,
                  "Exception caught...", e);
            }            
          }
        };

      self = threadPoolExecutor.submit(runnable);   
    }catch(RejectedExecutionException re){
      /* this exception will be thrown when wait and sweep is called more than twice.
       * threadPoolExecutor can have one running task and one waiting task.
       * */
      System.out.print(re);
      }catch (Exception e) {
      logEvent(StrategyEntry.ERROR, "waitAndSweep", symbol,
          "Exception caught...", e);
    }
  }
考虑调用方A:

private void callerA(){
waitandsweep();
waitandsweep();}
这包括两个任务,一个正在运行,另一个在队列中等待

protected void waitAndSweep(final String symbol) {
    try { 

        runnable = new Runnable() {
          @Override
          public void run() {
            try {
             // long sweepTime = symbolInfo.getSweepTime(symbol);
              // long timeSinceLastSweep = System.currentTimeMillis() - lastSliceSentTime;
              boolean sliceDone = Quant.equals(wave.getCommitedQuantity() % getSliceQuantity(),0);
              if(sliceDone){
                long timeSinceLastSliceQtySent = lastSliceSentTime == 0 ? getInterval() : System.currentTimeMillis() - lastSliceSentTime;
                long waitTime = timeSinceLastSliceQtySent >= getInterval() ? 0 : getInterval() - timeSinceLastSliceQtySent;
                logTradeEvent("waitAndSweep", symbol, "waittime: " + waitTime);
                if (waitTime > 0){
                  Thread.sleep(waitTime);
                }
              }

              callSweep(symbol);
            } catch(InterruptedException ie){
              ie.printStackTrace();
            }
            catch (Exception e) {
              logEvent(StrategyEntry.ERROR, "waitAndSweep", symbol,
                  "Exception caught...", e);
            }            
          }
        };

      self = threadPoolExecutor.submit(runnable);   
    }catch(RejectedExecutionException re){
      /* this exception will be thrown when wait and sweep is called more than twice.
       * threadPoolExecutor can have one running task and one waiting task.
       * */
      System.out.print(re);
      }catch (Exception e) {
      logEvent(StrategyEntry.ERROR, "waitAndSweep", symbol,
          "Exception caught...", e);
    }
  }
考虑被调用方b:

private void callerB(){
self.cancel(true);
waitandsweep();}
期望callerB取消A调用的所有任务。 事实上这并没有发生。。调用方B调用的任务被拒绝,因为队列中已经有一个任务在等待。你能告诉我为什么会发生这种行为吗


编辑1:如何取消executor正在运行的任务?

问题是,
未来。取消(布尔值)
不会从队列中删除任务。任务一旦被
执行器拉入,将不会执行,但在此之前它仍在队列中

尝试使用
threadPoolExecutor.purge()紧接着
取消()它将尝试删除已取消的任务

取消正在运行的任务并不是那么容易,您可以尝试以下操作:
调用
cancel(真)它将
Thread.interrupted()
设置为
true
。现在,在任务中检查一些有价值的步骤,以便决定跳过任务的后续步骤

如何从队列中删除任务。运行中的任务会被cancel方法终止吗?@user5367186您实际上不能“终止”任务。您需要在您的应用程序中检查“interrupted”/“isCanceled”-值Task@user5367186它将被自动中断,并抛出一个
InterruptedException
。因此,如果您调用
cancel(true)
,您将进入
catch(InterruptedException ie)
@user5367186是的,它将通过抛出
InterruptedException来中断