import java.util.ArrayList;
import java.util.concurrent.*;
class LiftOff implements Callable<String> {
private int id;
public LiftOff(int id) {
this.id = id;
}
@Override
public String call() throws Exception {
// TODO Auto-generated method stub
return "发射成功,发射火箭编号" + 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 block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
exec.shutdown();
}
}
}
import java.util.concurrent.*;
class LiftOff implements Callable<String> {
private int id;
public LiftOff(int id) {
this.id = id;
}
@Override
public String call() throws Exception {
// TODO Auto-generated method stub
return "发射成功,发射火箭编号" + 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 block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.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());
}
未完待续~~~~~~~~