Callable接口代替Runnable实现线程具有返回值
解决方法:
例子,统计1-100的和,并返回结果。
1.线程类
import java.util.concurrent.Callable;
public class CallableDemo implements Callable<String> {
private int begin;
private int end;
private int sum;
public CallableDemo(int begin, int end) {
super();
this.begin = begin;
this.end = end;
}
public String call() throws Exception {
for(int i=begin;i<=end;i++){
sum+=i;
}
return begin+"-" +end+"的和:"+ sum;
}
}
2.测试方法
public static void main(String[] args) throws Exception {
CallableDemo callable = new CallableDemo(1,100);
String call = callable.call();
}
3.结果
1-100的和:5050
本文链接:http://www.yayihouse.com/yayishuwu/chapter/1542