2015-10-05 72 views
0

包样本;如何取消执行者的运行任务

import java.util.TimerTask; 
import java.util.concurrent.ArrayBlockingQueue; 
import java.util.concurrent.Future; 
import java.util.concurrent.RejectedExecutionException; 
import java.util.concurrent.ThreadPoolExecutor; 
import java.util.concurrent.TimeUnit; 

public class ThreadPoolExecutorEg { 
    TimerTask timerTask; 
    int oneThread  = 1; 
    long zeroKeepAlive = 0L; 
    int queueDepthOfOne = 1; 

    ThreadPoolExecutor threadPoolExecutor = 
     new ThreadPoolExecutor(
       oneThread, 
       oneThread, 
       zeroKeepAlive, 
       TimeUnit.MILLISECONDS, 
       new ArrayBlockingQueue<Runnable>(queueDepthOfOne) 
     ); 
    private volatile static Future<?> self; 
public static void main(String args[]){ 
    ThreadPoolExecutorEg myTimer = new ThreadPoolExecutorEg(); 
    myTimer.waitAndSweep("A"); 
    myTimer.waitAndSweep("B"); 

    cancel(); 
    myTimer.waitAndSweep("replace"); 
    myTimer.waitAndSweep("B"); 

} 

private static void cancel() { 
self.cancel(true); 
System.out.println(self.isCancelled()); 
} 

public void waitAndSweep(final String caller) { 
    try { 


     timerTask = new TimerTask() { 

     @Override 
     public void run() { 
      try { 
      long waitTime = 1000; 
      if (waitTime > 0){ 
       Thread.sleep(waitTime); 
      } 

      } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
      } 
      System.out.println(caller); 
     } 
     }; 

    self = threadPoolExecutor.submit(timerTask); 


    }catch(RejectedExecutionException re){ 
System.out.println(re); 
    } 
    catch (Exception e) { 

    } 
} 
} 

在取消方法中,运行中的任务不会被取消。任何方式来取消正在运行的任务,即使线程正在休眠我想中断线程从睡眠并杀死整个任务?

取消(true)可能会失败的情况是什么?

+1

至少有一半不需要这里的代码或什么都不做。你可以简化这个例子,使它更容易理解。 –

回答

0

你需要的是List<Future<?>> self;在你的代码的问题是,你在每一个submit覆盖self而在需要分开存放submitFuture回报。

也能改变你waitAndSweep方法:

self.add(threadPoolExecutor.submit(timerTask))

+0

虽然这可能是一个问题,但OP一次只提交一个任务并尝试取消上一个任务。 –

+0

为什么我们需要维护未来的清单? – user5367186

+0

看起来像'cancelAll'意.. – harsh

相关问题