汶上县住房和城乡规划建设局官方网站,万网域名续费优惠,外贸信托,海淀注册公司在创建多线程程序的时候#xff0c;我们常实现Runnable接口#xff0c;Runnable没有返回值#xff0c;要想获得返回值#xff0c;Java5提供了一个新的接口Callable#xff0c;可以获取线程中的返回值#xff0c;但是获取线程的返回值的时候#xff0c;需要注意#xff…在创建多线程程序的时候我们常实现Runnable接口Runnable没有返回值要想获得返回值Java5提供了一个新的接口Callable可以获取线程中的返回值但是获取线程的返回值的时候需要注意我们的方法是异步的获取返回值的时候线程任务不一定有返回值所以需要判断线程是否结束才能够去取值。
测试代码
package com.wuwii.test;import java.util.concurrent.*;/*** author Zhang Kai* version 1.0* since pre2017/10/31 11:17/pre*/
public class Test {private static final Integer SLEEP_MILLS 3000;private static final Integer RUN_SLEEP_MILLS 1000;private int afterSeconds SLEEP_MILLS / RUN_SLEEP_MILLS;// 线程池根据机器的核心数private final ExecutorService fixedThreadPool Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());private void testCallable() throws InterruptedException {FutureString future null;try {/*** 在创建多线程程序的时候我们常实现Runnable接口Runnable没有返回值要想获得返回值Java5提供了一个新的接口Callable** Callable需要实现的是call()方法而不是run()方法返回值的类型有Callable的类型参数指定* Callable只能由ExecutorService.submit() 执行正常结束后将返回一个future对象。*/future fixedThreadPool.submit(() - {Thread.sleep(SLEEP_MILLS);return The thread returns value.;});} catch (Exception e) {e.printStackTrace();}if (future null) return;for (;;) {/*** 获得future对象之前可以使用isDone()方法检测future是否完成完成后可以调用get()方法获得future的值* 如果直接调用get()方法get()方法将阻塞到线程结束很浪费。*/if (future.isDone()) {try {System.out.println(future.get());break;} catch (InterruptedException | ExecutionException e) {e.printStackTrace();}} else {System.out.println(After afterSeconds-- seconds,get the future returns value.);Thread.sleep(1000);}}}public static void main(String[] args) throws InterruptedException {new Test().testCallable();}
}
运行结果
After 3 seconds,get the future returns value.
After 2 seconds,get the future returns value.
After 1 seconds,get the future returns value.
The thread returns value.总结:
需要返回值的线程使用Callable 接口实现call 方法获得future对象之前可以使用isDone()方法检测future是否完成完成后可以调用get()方法获得future的值如果直接调用get()方法get()方法将阻塞到线程结束。