创建线程方式三

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Demo_05 {

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		//创建线程 完成求两个整数的和
		SonRunnable sr = new SonRunnable(10, 20);
		Thread t = new Thread(sr);
		t.start();
		/*创建线程的方式三
		 * 		1.实现Callable接口 同时定义call方法的返回值类型
				2.重写call方法 线程要运行的代码
				3.创建FutureTask对象 将Callable接口实现类进行转换 获取结果
				4.创建Thread类 传入FutureTask对象
				5.调用FutureTask的get方法 获取call方法的返回值
				
				Callable 产生结果
				FutureTask 获取结果
		 * */
		SonCallable sc = new SonCallable(20, 30);
		FutureTask<Integer> ft = new FutureTask<>(sc);//FutureTask 是Runnable的实现类
		Thread t2 = new Thread(ft);
		t2.start();
		//获取call方法的返回值 调用FutureTask的get方法
		Integer i = ft.get();
		System.out.println(i);
	}

}
class SonCallable implements Callable<Integer>{
	private int a;
	private int b;
	public SonCallable(int a,int b){
		this.a = a;
		this.b = b;
	}
	@Override
	public Integer call() throws Exception {
		System.out.println(Thread.currentThread().getName()+":::"+(a+b));
		return a + b;
	}
	
}
class SonRunnable implements Runnable{

	private int a;
	private int b;
	public SonRunnable(int a,int b){
		this.a = a;
		this.b = b;
	}
	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName()+"求和..."+(a+b));
		//return a+b;
		//int x = 10/0; 如果run方法中出现异常 只能使用 try...catch 处理
	}
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值