将callable 封装到FutureTask
将futureTask submit 到线程池,并测试cancel 逻辑
启动两个线程,主线程在指定时机cancel 到提交到线程池的task ,
public class TestThread {
public static void main(String[] args) {
//定义一个task
Callable callable = new Callable<String>() {
@Override
public String call() throws Exception {
int i = 0;
while (true){
try {
Thread.currentThread().sleep(3000);
System.out.println("start to count : " + i);
i++;
if (i == 6)return "ok";
}catch (InterruptedException e){
System.out.println(" test : interruped");
throw e;
}
}
}
};
// 用future 包装task
FutureTask<String> futureTask = new FutureTask<>(callable);
//启动一个线程池
ExecutorService executorService = Executors.newSingleThreadExecutor();
// 将task 提交到线程池
Future<?> submit = executorService.submit(futureTask);
// 主线程去取消task
int i = 0;
while (true){
try {
i++;
Thread.currentThread().sleep(3000);
System.out.println("main start for i="+i);
if (i == 3){
boolean cancel = submit.cancel(true);
if (cancel){
System.out.println("canceled , not ok ");
}else {
System.out.println("get result : " + submit.get());
}
}
}catch (Exception e){
System.out.println(" test error main thread");
}
}
}
网友评论