java并发编程,通过Future取消任务
功能:通过Executor框架提供的线程池,提交任务,使用Future取消任务
任务:增长序列号,从0开始隔1s增长1
通过Future指定时间取消任务
IncrementSequence.java
1 /** 2 * 1s中增长1 3 * @author Administrator 4 * 5 */ 6 public class IncrementSequence implements Runnable{ 7 public int sequence = 0; 8 9 @Override 10 public void run() { 11 try { 12 while(true){ 13 sequence ++; 14 System.out.println("sequence = " + sequence); 15 //出现中断,抛出异常interruptexception,线程中断状态被清除 16 Thread.sleep(1000); 17 } 18 } catch (InterruptedException e) { 19 e.printStackTrace(); 20 } 21 22 } 23 }
CancelTaskUsingFuture.java
1 import java.util.concurrent.ExecutionException; 2 import java.util.concurrent.ExecutorService; 3 import java.util.concurrent.Executors; 4 import java.util.concurrent.Future; 5 import java.util.concurrent.TimeUnit; 6 import java.util.concurrent.TimeoutException; 7 8 /** 9 * 使用Future取消任务 10 * @author Administrator 11 * 12 */ 13 public class CancelTaskUsingFuture { 14 //线程池 15 private static ExecutorService taskExec = Executors.newFixedThreadPool(1); 16 17 /** 18 * 指定执行任务时间,时间到通过future取消任务的执行 19 * @param r 20 * @param timeOut 21 * @param unit 22 */ 23 public static void timeRun(Runnable r, long timeOut, TimeUnit unit){ 24 Future<?> task = taskExec.submit(r); 25 try { 26 task.get(timeOut, unit); //等待超时,等待给定的时间之后,获取其结果 27 } catch (InterruptedException | ExecutionException | TimeoutException e) { 28 e.printStackTrace(); 29 } finally{ 30 task.cancel(true); 31 //关闭线程池 32 taskExec.shutdown(); 33 } 34 35 } 36 37 /** 38 * 测试程序 39 * @param args 40 */ 41 public static void main(String args[]){ 42 Runnable scirpt = new IncrementSequence(); 43 44 //10s后结束任务 45 timeRun(scirpt, 10, TimeUnit.SECONDS); 46 } 47 }
Please call me JiangYouDang!