多執行緒實現非同步計算
阿新 • • 發佈:2018-12-01
package cn.itcast.demo6;
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 f1 =es.submit(new GetSumCallable(100));
Future f2 =es.submit(new GetSumCallable(200));
System.out.println(f1.get());
System.out.println(f2.get());
es.shutdown();
}
}
package cn.itcast.demo6;
import java.util.concurrent.Callable;
public class GetSumCallable implements Callable{
//利用構造器來控制各個執行緒的傳參 private int a; public GetSumCallable(int a){ this.a=a; } public Integer call(){ int sum = 0 ; for(int i = 1 ; i <=a ; i++){ sum = sum + i ; } return sum; }
}