使用FutureTask

1.new一个Callable<V>对象


2.用callable对象构造一个FutureTask<V>


3.用FutureTask对象构造一个Thread,并调用thread的start


4.调用FutureTask对象的get方法


下面的代码来自《java核心技术:卷1》


package test.futureTaskTest;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Main {
	public static void main(String[] args) {
//		Scanner in = new Scanner(System.in);
//		System.out.println("input dir:");
//		String dir = in.nextLine();
//		System.out.println("input key:");
//		String key = in.nextLine();
		
		String dir = "d:/logs", key = "2013";
		
		MatchCallable match = new MatchCallable(new File(dir), key);
		FutureTask<Integer> futureTask = new FutureTask<Integer>(match);
		Thread t = new Thread(futureTask );
		t.start();
		
		try {
			System.out.println(futureTask.get());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}
	static class MatchCallable implements Callable<Integer> {
		
		private final File dir;
		private final String key;
		
		public MatchCallable(File dir, String key) {
			this.dir = dir;
			this.key = key;
		}

		@Override
		public Integer call() throws Exception {
			Integer count = 0;
			File[] files = null;
			try {
				System.out.println("isDir:" + dir.isDirectory() + "    isFile:" + dir.isFile() + "    " + dir);
				files = dir.listFiles();
				List<FutureTask<Integer> > list = new LinkedList<FutureTask<Integer> >();
				for (File file : files) {
					if (file.isFile()) {
						if (search(file))
							++count;
					} else {
						MatchCallable match = new MatchCallable(file, key);
						FutureTask<Integer> futureTask = new FutureTask<Integer>(match);
						list.add(futureTask);
						Thread t = new Thread(futureTask );
						t.start();
					}
				}
				for (FutureTask<Integer> ftask : list) {
					count += ftask.get();
				}
				return count;
			}catch (Throwable e) {
				return count;
			}
		}
		
		private boolean search(File file) {
			boolean found = false;
			try {
				Scanner in = new Scanner(file);
				while (!found && in.hasNextLine()) {
					if (in.nextLine().contains(key)) {
						found = true;
					}
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			return found;
		}
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值