Java java.util.concurrent.Future的一个例子
2024-07-19 09:17:30 阅读次数:17
java,编程开发
package callableTest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class CallableIndicator{
private String name;
private Double result;
static public final int TIME = 3000;
public CallableIndicator(String name, Double result){
this.name = name;
this.result = result;
}
public Double getResult(){
return this.result;
}
public String getName(){
return this.name;
}
}
public class CallableTest {
private static final int POOL_SIZE = 2;
static class CalcThread implements Callable<CallableIndicator> {
private String name;
private List<Double> dataList = new ArrayList<>();
public CalcThread(String name) {
for(int i = 0; i < 10000; ++i) {
dataList.add(Math.random());
}
this.name = name;
System.out.println("In CalcThread constructor, thread id: " +
Thread.currentThread().getId());
}
@Override
public CallableIndicator call() throws Exception {
double total = 0;
for(Double d : dataList) {
total += d;
}
System.out.println("In CalcThread @Override call(), thread id: " +
Thread.currentThread().getId());
Thread.sleep(CallableIndicator.TIME);
return new CallableIndicator(this.name, total / dataList.size());
}
}
public static void printThread(){
System.out.println("In main Thread? " + Thread.currentThread().getId());
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
List<Future<CallableIndicator>> fList = new ArrayList<>();
ExecutorService es = Executors.newFixedThreadPool(POOL_SIZE);
printThread();
System.out.println("Ready to submit new thread...");
for(int i = 0; i < POOL_SIZE; ++i) {
fList.add(es.submit(new CalcThread("Jerry Thread: " + i)));
}
for(Future<CallableIndicator> f : fList) {
try {
/*
* 注意这个get是异步操作:The result can only be retrieved using method get when the computation has completed, blocking if necessary until it is ready.
*/
System.out.println("Thread name: " + f.get().getName() + " result: " + f.get().getResult());
} catch (Exception e) {
e.printStackTrace();
}
}
long end = System.currentTimeMillis();
System.out.println("duration: " + ( end - start));
es.shutdown();
}
}
版权声明:本文内容来自第三方投稿或授权转载,原文地址:https://blog.51cto.com/jerrywangsap/5205929,作者:JerryWang汪子熙,版权归原作者所有。本网站转在其作品的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如因作品内容、版权等问题需要同本网站联系,请发邮件至ctyunbbs@chinatelecom.cn沟通。
上一篇:用Eclipse调试Java程序的一些小技巧
下一篇:使用Java标准的java.util.EventListener实现观察者-发布者设计模式