多线程之Callable项目实战总结

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());
			}
		}
	
	}
	
}

多做总结,多做演练

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值