从头认识java-17.6 Callable、Future和FutureTask

页面导航:首页 > 软件编程 > Java编程 > 从头认识java-17.6 Callable、Future和FutureTask

从头认识java-17.6 Callable、Future和FutureTask

来源: 作者: 时间:2016-01-18 15:52 【

这一章节我们来讨论一下Callable、Future和FutureTask的用法与关系。1 关系(1)Callable是Runnable的封装的异步运算任务(2)Future用来保存Callable异步运算的结果(3)FutureTask封装Future的实体类

这一章节我们来讨论一下Callable、Future和FutureTask的用法与关系。

1.关系

(1)Callable是Runnable的封装的异步运算任务

(2)Future用来保存Callable异步运算的结果

(3)FutureTask封装Future的实体类

2.Future

我们在这里详细介绍一下Future,因为它比较复杂,首先看看他的源代码:

public interface Future { 
    boolean cancel(boolean mayInterruptIfRunning); 
    boolean isCancelled(); 
    boolean isDone(); 
    V get() throws InterruptedException, ExecutionException; 
    V get(long timeout, TimeUnit unit) 
        throws InterruptedException, ExecutionException, TimeoutException; 
} 


它里面包含了几个方法

get:得到结果

get(timeout,unit)计算是否超时得到结果

cancle:取消任务

isDone、isCancle:判断任务状态

 

3.例子:

Callable和FutureTask

package com.ray.ch17;

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

public class Test {

	public static void main(String[] args) throws InterruptedException,
			ExecutionException {
		Callable callable = new MyCall();
		FutureTask futureTask = new FutureTask(callable);
		Thread thread = new Thread(futureTask);
		thread.start();
		Thread.sleep(100);
		if (!futureTask.isDone()) {
			System.out.println(futureTask.get());
		}
		if (!futureTask.isCancelled()) {
			futureTask.cancel(true);
			System.out.println("cancelled");
		}

	}
}

class MyCall implements Callable {

	@Override
	public Integer call() throws Exception {
		System.out.println("doing something...");
		Thread.sleep(1000);
		return new Random().nextInt(50);
	}
}


我们只需要将上面main方法里面的两个if互换就可以得出不同的结果。

Callable和Future

package com.ray.ch17;

import java.util.Random;
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;

public class Test {

	public static void main(String[] args) throws InterruptedException,
			ExecutionException {
		ExecutorService executors = Executors.newCachedThreadPool();
		Callable callable = new MyCall();
		Future future = executors.submit(callable);
		System.out.println(future.get());
	}
}

class MyCall implements Callable {

	@Override
	public Integer call() throws Exception {
		System.out.println("doing something...");
		Thread.sleep(1000);
		return new Random().nextInt(50);
	}
}

总结:这一章节主要介绍了Callable、Future和FutureTask的用法与关系。

Tags:

文章评论

最 近 更 新
热 点 排 行
Js与CSS工具
代码转换工具

<