package com.yang;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class TestVolatile {
public static void main(String[] args) {
//相比较实现Runable接口而言有返回值,可以抛出异常
ThreadDemo td=new ThreadDemo();
// Callable执行需要FutureTask实现类的支持 FutureTask 也可以用于闭锁
FutureTask<Integer>result=new FutureTask<>(td);
new Thread(result).start();
try {
Integer sum=result.get();
System.out.println(sum);
System.out.println("=============");
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ThreadDemo implements Callable<Integer>{
@Override
public Integer call() throws Exception {
// TODO Auto-generated method stub
int sum=0;
for(int i=0;i<=100;i++) {
sum+=i;
System.out.println(sum);
}
return sum;
}
}
线程实现callable接口
最新推荐文章于 2024-04-07 11:47:05 发布