FutureTask异步方法的使用

   FutureTask类是java中提供的异步计算类。我们首先来看一下它的定义:

  A cancellable asynchronous computation. This class provides a base implementation of Future, with methods to start and cancel a computation, query to see if the computation is complete, and retrieve the result of the computation. The result can only be retrieved when the computation has completed; the get methods will block if the computation has not yet completed. Once the computation has completed, the computation cannot be restarted or cancelled (unless the computation is invoked using runAndReset()).
  A FutureTask can be used to wrap a Callable or Runnable object. Because FutureTask implements Runnable, a FutureTask can be submitted to an Executor for execution.
  In addition to serving as a standalone class, this class provides protected functionality that may be useful when creating customized task classes.

  粗略的翻译一下就是:

 FutureTask类是一个异步的可以取消的计算。这个类的实现是基于实现了Future接口的,所以它有包括开始/取消计算、查询计算是否完成和检索计算结果的方法。计算结果只有在计算完成之后才可以查到;get()方法再计算完成之前调用会被阻塞。一旦一个计算完成,这个计算就不能够被重启和取消。FutureTask类能够用来包装callable和Runnable对象。

FutureTask在实际运用中,最主要的用法就是包装Callable对象和Runnable对象。因为FutureTask对象实现了Runnable接口,所以可以直接设置为Thread对象中的target属性,这样FutureTask对象就可以在多线程中完成计算。或者更加片面的说,FutureTask可以把Callable对象包装成Runnable和Future,这样既可以多线程的运行,又可以异步的获取计算结果。

  下面这个例子,查询某个目录下的文件个数,不包括目录数:

MyFutureWork.java

 

package com.app.future;

import java.io.File;
import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

//计算目录中文件的个数,不包括目录
public class MyFutureWork implements Callable<Integer> {

	File f = null;

	public MyFutureWork(File path) {
		this.f = path;
	}

	@Override
	public Integer call() throws Exception {
		int count = 0;
		File[] files = f.listFiles();
		ArrayList<FutureTask<Integer>> al = new ArrayList<FutureTask<Integer>>();
		for (File f : files) {
			if (f.isFile()) {
				count++;
			} else if (f.isDirectory()) {
				MyFutureWork work = new MyFutureWork(f);       //递归的调用
				FutureTask<Integer> task = new FutureTask<Integer>(work);
				al.add(task);
			}
		}
		for (FutureTask<Integer> task : al) {
			Thread t = new Thread(task);
			t.start();
			count += task.get();
		}
		return count;
	}

}


FutureClient.java

package com.app.future;

import java.io.File;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class FutureClient {

	public static void main(String[] args) {

		File f = new File("e:/OOAD与UML");

		MyFutureWork work = new MyFutureWork(f);

		FutureTask<Integer> task = new FutureTask<Integer>(work);

		Thread t = new Thread(task);

		t.start();

		try {
			
			System.out.println("count:" + task.get());

		} catch (InterruptedException e) {

			e.printStackTrace();
			
		} catch (ExecutionException e) {

			e.printStackTrace();
		}

	}

}


 执行结果:

FutureTask异步方法的使用

你可能感兴趣的:(java,FutureTask)