- java实现多线程的方式有:继承Thread类;实现Runnable接口;实现Callable接口;
- 实现Callable接口,需要FutureTask类的支持,用于接收运算的结果,FutureTask类实现了Future接口和Runnable接口;
- Callable的任务执行后可以有返回值,并且可以抛出异常;
import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; public class TestDemo { public static void main(String[] args) { ThreadDemo td = new ThreadDemo(); FutureTask<Integer> result = new FutureTask<Integer>(td); new Thread(result).start(); try{ //FutureTask 可用于 闭锁 类似于CountDownLatch的作用,在所有的线程没有执行完成之后这里是不会执行的 Integer sum = result.get(); System.out.println(sum); } catch(Exception e) { e.printStackTrace(); } } } class ThreadDemo implements Callable<Integer> { @Override public Integer call() throws Exception { int sum = 0; for (int i = 0; i <= 100000; i ++) { sum += i; } return sum; } }