Java之Callable 和 Future实现线程等待

1、Callable:
public interface Callable<V>
 
 

返回结果并且可能抛出异常的任务。实现者定义了一个不带任何参数的叫做 call 的方法。

Callable 接口类似于 Runnable,两者都是为那些其实例可能被另一个线程执行的类设计的。但是 Runnable 不会返回结果,并且无法抛出经过检查的异常。

Executors 类包含一些从其他普通形式转换成 Callable 类的实用方法。

call

V call()
       throws Exception
计算结果,如果无法计算结果,则抛出一个异常。 

返回:
计算的结果
抛出:
Exception - 如果无法计算结果
2、Future:
public interface Future<V>
 
 

Future 表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并获取计算的结果。计算完成后只能使用 get 方法来获取结果,如有必要,计算完成前可以阻塞此方法。取消则由 cancel 方法来执行。还提供了其他方法,以确定任务是正常完成还是被取消了。一旦计算完成,就不能再取消计算。如果为了可取消性而使用 Future 但又不提供可用的结果,则可以声明 Future<?> 形式类型、并返回 null 作为底层任务的结果。

get

V get()
      throws InterruptedException,
             ExecutionException
如有必要,等待计算完成,然后获取其结果。 

返回:
计算的结果
抛出:
CancellationException - 如果计算被取消
ExecutionException - 如果计算抛出异常
InterruptedException - 如果当前的线程在等待时被中断
3、相关实例:
<pre name="code" class="java">public class TestFutureTask {
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		final ExecutorService exec = Executors.newFixedThreadPool(5);
		Callable<String> call = new Callable<String>() {
			public String call() throws Exception {
				Thread.sleep(1000 * 3);// 休眠指定的时间,此处表示该操作比较耗时
				return "Other less important but longtime things.";
			}
		};
		Future<String> task = exec.submit(call);
		//Thread.sleep(1000 * 3);
		System.out.println("Let's do important things.");
		//如果线程内部的事情还未处理完,即还没有返回结果,则会阻塞
		boolean isDone = task.isDone();
		while(!isDone){
			isDone = task.isDone();
		}
		String obj = task.get();
		System.out.println(obj);
		// 关闭线程池
		exec.shutdown();
	}
}


输出结果:
 
 
Let's do important things.
Other less important but longtime things.
转载:http://www.itzhai.com/callable-and-future-realization-of-the-thread-waiting-for.html
 
 
其他
public class TestFutureTask2 {
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		final ExecutorService exec = Executors.newFixedThreadPool(5);
		Runnable runnable = new Runnable() {
			
			@Override
			public void run() {
				try {
					Thread.sleep(1000 * 2);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}// 休眠指定的时间,此处表示该操作比较耗时
			}
		};
		Future<String> task = exec.submit(runnable, "aa");


		System.out.println("Let's do important things.");
		//如果线程内部的事情还未处理完,即还没有返回结果,则会阻塞
		boolean isDone = task.isDone();
		while(!isDone){
			//Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds,
			Thread.sleep(500);
			isDone = task.isDone();
		}
		String obj = task.get();
		System.out.println(obj);//输出aa,即上面submit方法传入的参数
		// 关闭线程池
		exec.shutdown();
	}
}
 
 
 
 
public class TestFutureTask3 {
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		final ExecutorService exec = Executors.newFixedThreadPool(5);
		Runnable runnable = new Runnable() {
			
			@Override
			public void run() {
				try {
					Thread.sleep(1000 * 2);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}// 休眠指定的时间,此处表示该操作比较耗时
			}
		};
		Future<?> task = exec.submit(runnable);


		System.out.println("Let's do important things.");
		// 不重要的事情
		//如果线程内部的事情还未处理完,即还没有返回结果,则会阻塞
		boolean isDone = task.isDone();
		while(!isDone){
			//Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds,
			Thread.sleep(500);
			isDone = task.isDone();
		}
		String obj = (String) task.get();
		System.out.println(obj);//输出null
		// 关闭线程池
		exec.shutdown();
	}
}
 
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值