JAVA基础 线程池、callable

124 篇文章 1 订阅
96 篇文章 0 订阅





package demo;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ExecutorDemo {
	
	public static void main(String[] args) {
		//创建线程池
		ExecutorService es = Executors.newFixedThreadPool(2);
		
		//ExecutorService传入runable来运行
//		es.submit(new MyRunable());
//		es.shutdown();
		
		//ExecutorService传入callable来运行,可以处理异常、返回结果。
		try {
			Future<String> retStr = es.submit(new MyCallable());
			System.out.println(retStr.get());
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			es.shutdown();
		}

		
	}
}
class MyCallable implements Callable<String>{

	@Override
	public String call() throws Exception {
		
		return Thread.currentThread().getName()+":正在运行";
	}
	
}
class MyRunable implements Runnable{

	@Override
	public void run() {
		// TODO Auto-generated method stub
		System.out.println(Thread.currentThread().getName() + ": 正在运行。");
		
	}
	
}



练习:

        通过线程池中的线程对象,使用Callable接口完成两个数求和操作

package demo;

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

public class Test2 {
/*
 * 要求:通过线程池中的线程对象,使用Callable接口完成两个数求和操作
 */
	public static void main(String[] args) throws Exception {
		ExecutorService es = Executors.newFixedThreadPool(2);
		
		Future<Integer> retInt = es.submit(new ICallable(1,2));
		System.out.println("Sum is : " + retInt.get());
		

	}

	
}

class ICallable implements Callable<Integer>{
	int x;
	int y;
	public ICallable() {
		super();
	}
	
	public ICallable(int x, int y) {
		super();
		this.x = x;
		this.y = y;
	}

	@Override
	public Integer call() throws Exception {
		
		return x+y;
	}
	
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值