package com.trg.test;
import java.util.concurrent.Callable;
public class CalcCallable implements Callable<Double> {
private double num1;
private double num2;
private String type;
public CalcCallable() {
super();
}
public CalcCallable(double num1, double num2,String type) {
super();
this.num1 = num1;
this.num2 = num2;
this.type = type;
}
public double getNum1() {
return num1;
}
public void setNum1(double num1) {
this.num1 = num1;
}
public double getNum2() {
return num2;
}
public void setType(String type) {
this.type = type;
}
public String getType() {
return type;
}
public Double call() throws Exception {
// TODO Auto-generated method stub
return this.calc(num1, num2, type);
}
//计算两个数的加、减、乘、除
public Double calc(double num1,double num2,String type){
double result = 0;
switch(type)
{
case "+":
result = num1+num2;
break;
case "-":
result = num1+num2;
break;
case "*":
result = num1+num2;
break;
case "/":
result = num1+num2;
break;
}
return result;
}
}
package com.trg.test;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CallableTest {
/**
* Callable实际使用演示
* @throws ExecutionException
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException, ExecutionException {
int num1 = 12;
int num2 = 12;
String type ="+";
call(num1,num2,type);
}
public static void call(int num1,int num2,String type) throws InterruptedException, ExecutionException{
//开启一个线程池
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
Map<String,Future<Double>> map = new HashMap();
for(int i=0;i<12;i++){
for(int j=0;j<12;j++){
map.put(i+"&&"+j, cachedThreadPool.submit(new CalcCallable(i, j,"+")));
}
}
//关闭
cachedThreadPool.shutdown();
if(cachedThreadPool.isTerminated()){
for(String key:map.keySet()){
System.out.println(key+"="+map.get(key).get());
}
}
}
}
多做总结,多做演练