?
class="中断举例 ">package com.java.util.concurrent; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Test1 { public static void main(String[] args) throws Exception { ExecutorService exeService = Executors.newFixedThreadPool(1); Future<Thread> future = exeService.submit(new CallableC<CallObj>(new CallObj())); // exeService.submit(new CallableC<CallObj>(new CallObj())); blocking quene Thread s = future.get();// get() is blocking System.out.println(s); System.out.println(s.isInterrupted()); } static class CallObj{ @Override public String toString() { return System.currentTimeMillis()+""; } } static class CallableC<V> implements Callable{ private V obj ; public CallableC(V o) { obj = o; } @Override public Thread call() throws Exception { System.out.println("start....."); int i = 0; try { while (true) { call(obj); Thread.sleep(1000);// in sleep(),weather interrupted; i=7,currentThread is interrupted i++; if(i>5)// 7 times ; i=6 currentThread.interrupt() Thread.currentThread().interrupt(); } } catch (Exception e) { e.printStackTrace(); }finally{ System.out.println("done....."); } return Thread.currentThread(); } public String call(V arg){ System.out.println(Thread.currentThread().getName()); return null; } } }
中断特点:
?? 1. 只能中断线程阻塞 时
?? 2. 中断不影响thread代码逻辑,只是一个标志位的改变和中断异常的表示
?
?
??? Thread.currentThread().interrupt(); 会把Thread,中断标志位 标志为 true,
??? Thread.sleep() ; 方法内部Thread会判断当前线程的中断标志位,为true,则抛出中断异常
??? Thread被中断(这里(上面的代码)是指抛出中断异常了),thread仍继续执行,如果没有使用中断标志位进行其它的逻辑处理,中断就没有意义
??
?
?
?
?
?
?
?