java Callable使用实例

多个线程实现累加


package com.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author:xxx
 * @TODO:使用callable进行自增
 */
public class AddCallable {
	public static void main(String[] args) {
		long begin = System.currentTimeMillis();
		ExecutorService threadPool = Executors.newCachedThreadPool();
		AddTask task01 = new AddTask("Task-01", 1, 50);
		AddTask task02 = new AddTask("Task-02", 51, 100);
		//得到的结果集
		Future<Long> resultSet01 = threadPool.submit(task01);
		Future<Long> resultSet02 = threadPool.submit(task02);
		try {
			System.out.println("最后的结果是:"+(resultSet01.get()+resultSet02.get()));
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		finally{
			threadPool.shutdown();
		}
		System.out.println(System.currentTimeMillis() - begin);
	}
};

/**
 * @author:xxx
 * @TODO:泛型中的Long表示返回的类型
 */
class AddTask implements Callable<Long> {
	private String name;
	private long begin;
	private long end;

	public AddTask(String name, long begin, long end) {
		this.name = name;
		this.begin = begin;
		this.end = end;
	}

	@Override
	public Long call() throws Exception {
		System.out.println(Thread.currentThread().getName());
		System.out.println(name + " 执行中.......");
		long sum = 0;
		for (long i = begin; i <= end; i++) {
			sum += i;
		}
		return sum;
	}
};


例子 2


/**
 * 
 */
package com.comtop.test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @ProjectName:Skeleton
 * @PackageName:com.comtop.test
 * @Verson :0.1
 * @CreateUser :lanweixing
 * @CreateDate :2014-9-3上午9:41:16
 * @UseFor :
 */
public class DoThread {
	
	public static void main(String[] args) {
		List<Num> list = new ArrayList<Num>();
		List<Message> result1 = new ArrayList<Message>();
		List<Message> result = new ArrayList<Message>();
		// ExecutorService pool = Executors.newCachedThreadPool() ;
		//使用线程池处理
		ThreadPoolExecutor pool = new ThreadPoolExecutor(3, 4, 3000L,
				TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnab
  • 0
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值