首页 > 编程 > Java > 正文

Java实例 改进发射小程序 java.util.concurrent.Callable接口 从任务中产生返回值

2019-11-08 18:49:51
字体:
来源:转载
供稿:网友
import java.util.ArrayList;import java.util.concurrent.*;class LiftOff implements Callable<String> {PRivate int id;public LiftOff(int id) {this.id = id;}@Overridepublic String call() throws Exception {// TODO Auto-generated method stubreturn "发射成功,发射火箭编号" + id;}}public class Test05 {public static void main(String[] args) {ExecutorService exec = Executors.newCachedThreadPool();ArrayList<Future<String>> results = new ArrayList<Future<String>>();for (int i = 0; i < 10; i++) {results.add(exec.submit(new LiftOff(i)));}for (Future<String> future : results) {try {System.out.println(future.get());} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ExecutionException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {exec.shutdown();}}}

}

运行结果:

发射成功,发射火箭编号0发射成功,发射火箭编号1发射成功,发射火箭编号2发射成功,发射火箭编号3发射成功,发射火箭编号4发射成功,发射火箭编号5发射成功,发射火箭编号6发射成功,发射火箭编号7发射成功,发射火箭编号8发射成功,发射火箭编号9

说明:

submit()方法会产生Future对象,用Callable的call()方法返回结果的特定类型进行来了参数化。

if(future.isDone()){System.out.println(future.get());}

未完待续~~~~~~~~


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表