執行緒實現非同步計算-求和
類GetSumCallable實現介面:
import java.util.concurrent.Callable;
public class GetSumCallable implements Callable<Integer> {
public Integer call(){
int sum=0;
for(int i=0;i<=100;i++)
sum=sum+i;
return sum;
}
}
類GetSumCallable2實現介面:
import java.util.concurrent.Callable;
public class GetSumCallable2 implements Callable<Integer> {
public Integer call(){
int sum=0;
for(int i=0;i<=200;i++)
sum=sum+i;
return sum;
}
}
測試Demo類:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/*
* 使用多執行緒技術,求和(執行緒池)
* 兩個執行緒,1個執行緒計算1+100;另一個執行緒計算1+200的和
* 多執行緒的非同步計算
*/
public class ThreadPoolDemo {
public static void main(String[] args) throws Exception {
ExecutorService es=Executors.newFixedThreadPool(2);
Future<Integer>f=es.submit(new GetSumCallable());
int s1=f.get();
System.out.println(s1);
Future<Integer>f1=es.submit(new GetSumCallable2());
int s2=f1.get();
System.out.println(s2);
}
}