使用Callable接口实现线程 —— Java编程思想之并发学习(二)

  • 使用Callable接口实现一个线程的代码如下:

package com.mec.about_bingfaThread;

import java.util.ArrayList;
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 橙橙橙。
 *
 */
public class LiftOff implements Callable<String>{
	private int id;
	
	public  LiftOff(int id) {
		this.id = id;
	}
	@Override
	public String call() throws Exception {
		return "the result is= " + id;
	}

	public static void main(String[] args) {
		ExecutorService exe = Executors.newCachedThreadPool();
		ArrayList<Future<String>> results = new ArrayList<>();
		for(int i = 0; i < 10; i++) {
			results.add(exe.submit(new LiftOff(i)));
		}
		for (Future<String> future : results) {
			try {
				System.out.println(future.get());
			} catch (InterruptedException | ExecutionException e) {
				e.printStackTrace();
			} finally{
				exe.shutdown();
			}
		}
		}
}

结果如下:

the result is= 0
the result is= 1
the result is= 2
the result is= 3
the result is= 4
the result is= 5
the result is= 6
the result is= 7
the result is= 8
the result is= 9

大家可以清楚的看到Callable与Runnable接口实现线程方式的不同之处:

  1. run()方法的返回值为void,二call()方法是有返回值,并且返回值的类型不是固定的,它可以是你自己指定的类型,因为在我们继承Calable时,它就是泛型;
  2. 在使用Executor中的方法执行任务时,我们调用的方法时execute(Runnable runn)方法,而在此处用到的是submit()方法,这个方法中的参数就是在实现Callable接口时自己定义的类;
  3. 此处的Future<>也是与Callable的子类匹配的集合;

而shutdown()的方法与上篇写到的应该是一致的,请参阅上一篇文章。

不妥之处,请大家多多指教~

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值