实现Callable接口来创建线程
使用Callable来创建线程,可以获得返回结果,并且可以抛出异常。
和Runnable的具体区别有:
1)Runnable重写的是run方法,Callable重写的是call方法。
2)Callable能够抛出exception,而Runnable不可以。
3)Callable能够得到返回结果,而Runnable不可以。
4)Callable和Runnable都可以应用于executors,而Thread类只支持Runnable。
借助线程池来实现:
public class TestCallable implements Callable<String> { @Override public String call() throws Exception { for (int i = 0; i < 100; i++) { System.out.println("测试"+i); } return "运行结束"; } public static void main(String[] args) throws ExecutionException, InterruptedException { //借助线程池来运行,创建执行服务 ExecutorService exec = Executors.newCachedThreadPool(); //提交执行 Future<String> future = exec.submit(new TestCallable()); //获得返回信息 System.out.println(future.get()); //关闭服务 exec.shutdown(); } }
借助FutureTask类来实现:
public class TestCallable implements Callable<String> { @Override public String call() throws Exception { for (int i = 0; i < 100; i++) { System.out.println("测试"+i); } return "运行结束"; } public static void main(String[] args) throws ExecutionException, InterruptedException { //开始线程 FutureTask<String> futureTask = new FutureTask<>(new TestCallable()); new Thread(futureTask).start(); //通过futuretask可以得到MyCallableTask的call()的运行结果: System.out.println(futureTask.get()); } }