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;
}
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仍继续执行,如果没有使用中断标志位进行其它的逻辑处理,中断就没有意义
本文通过一个具体的Java示例,展示了如何使用ExecutorService来管理和执行线程,并解释了线程中断的特点及其工作原理。同时,文章深入探讨了Future接口的使用方式及线程阻塞状态下的中断行为。
1900

被折叠的 条评论
为什么被折叠?



