Callable和Future

Callable

相对于Runnable,Callable并非很让人熟知,其实Callable和Runnable很相似,只不过它有返回值,而且也没有run()方法,而是有call()方法。java

public interface Callable<V>{
    V call() throw Exception;
}

Callable 接口相似于 Runnable,二者都是为那些其实例可能被另外一个线程执行的类设计的。可是 Runnable 不会返回结果,而且没法抛出通过检查的异常。异步

能够看到,返回的结果是以V泛型表示的,好比Callable<Integer>表示一个最终返回Integer的异步计算ide

Future

Future用来保存异步计算的结果,就是说以前用Callable标志的任务能够用Future来进行包装,那为何非要用Future呢,Callable本身运行而后用相应的类型来接收结果不就好了吗?之因此要用到Future,有一下两个缘由:测试

  1. Thread t = new Thread(..)用这个方法建立一个线程,必需要传给一个Runnable的参数,而不能传给它Callable
  2. Future对象具备一系列的方法,好比它的get方法可以被阻塞,直到计算完成;也能够在任务进行的过程当中取消它。这些方法使得它更便利

FutureTask

可是Future终究只是一个接口,而FutureTask包装器不只实现了Future接口,还实现了Runnable接口,这弥补上面的遗憾,使得它不只能被Thread运行,还具备取消运行的特性,一个典型的使用FutureTask的例子就是:this

Callable<Integer> calc = ...;
FutureTask<Integer> task = new FutureTask<Integer>(calc);
Thread t = new Thread(task);   //这里是Runnable
t.start;
...
Integer result = task.get();   //这里是Future

住:FutureTask的两个构造方法spa

FutureTask(Callable<V> task)线程

FutureTask(Runnable task,V result)设计

Demo

一个计算指定目录下具备指定关键字的文件数目的例子:code

package future;

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

public class MatchCounter implements Callable<Integer> {

	private File directory;
	private String keyword;
	private int count;

	public MatchCounter(File directory, String keyword) {
		this.directory = directory;
		this.keyword = keyword;
	}

	@Override
	public Integer call() throws Exception {
		count = 0;
		try {
			File[] files = directory.listFiles();
			List<Future<Integer>> results = new ArrayList<>(); // 用来保存全部的异步计算结果

			for (File file : files) {
				if (file.isDirectory()) {
					MatchCounter counter = new MatchCounter(file, keyword);
					FutureTask<Integer> task = new FutureTask<>(counter);
					results.add(task);
					Thread t = new Thread(task);
					t.start();
				} else {
					if (search(file)) {
						count++;
					}
				}
			}

			for (Future<Integer> r : results) {
				count += r.get();
			}
		} catch (InterruptedException e) {

		}
		return count;
	}

	public boolean search(File file) {
		try {
			Scanner in = new Scanner(file);
			boolean found = false;
			while (in.hasNextLine()) {
				String line = in.nextLine();
				if (line.contains(keyword)) {
					found = true;
				}
			}
			return found;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return false;

	}
}

测试类:对象

package future;

import java.io.File;
import java.util.Scanner;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class FutureTest {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		System.out.println("Enter starting directory:");
		String d = in.nextLine();
		System.out.println("Enter keyword:");
		String keyword = in.nextLine();

		MatchCounter counter = new MatchCounter(new File(d), keyword);
		FutureTask<Integer> task = new FutureTask<>(counter);

		new Thread(task).start();

		try {
			System.out.println(task.get() + " matching files!");
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}
}

运行:

Enter starting directory:
D:\workspace\concurrent\src
Enter keyword:
future
2 matching files!
相关文章
相关标签/搜索