标签:task cal down tst one 实现类 call() sys 实现
1.Runnable
ExecutorService executor = Executors.newCachedThreadPool(); executor.submit(new Runnable() { public void run() { //TODO } }); executor.shutdown();
public interface Callable<V> { V call() throws Exception; }
ExecutorService pool = Executors.newCachedThreadPool(); Future<String> future = pool.submit(new Callable{ public void call(){ //TODO } });
FutureTask<String> task = new FutureTask(new Callable{ public void call(){ //TODO } }); Thead thread = new Thread(task); thread.start();
public static <T> Callable<T> callable(Runnable task, T result) { if (task == null) throw new NullPointerException(); return new RunnableAdapter<T>(task, result);//通过RunnableAdapter实现 } static final class RunnableAdapter<T> implements Callable<T> { final Runnable task; final T result; RunnableAdapter(Runnable task, T result) { this.task = task; this.result = result; } public T call() { task.run(); return result; //将传入的结果的直接返回 } }
try{ future.get(60,TimeUtil.SECOND); }catch(TimeoutException timeout){ log4j.log("任务越野,将被取消!!"); future.cancel(); }
FutureTask(Callable<V> callable) FutureTask(Runnable runnable, V result)
5.应用
public class FileSearchTask { public static void main(String[] args) throws ExecutionException, InterruptedException { String path = args[0]; String keyword = args[1]; int c = 0; File[] files = new File(path).listFiles(); ArrayList<Future<Integer>> rs = new ArrayList<>(); for(File file: files){ //每个文件启动一个task去查找 MatchCount count = new MatchCount(); count.file = file; count.keyword = keyword; FutureTask<Integer> task = new FutureTask(count); rs.add(task); //将任务返回的结果添加到集合中 Thread thread = new Thread(task); thread.start(); } for(Future<Integer> f: rs){ c += f.get(); //迭代返回结果并累加 } System.out.println("包含关键字的总文件数为:" + c); } } class MatchCount implements Callable<Integer>{ public File file; public String keyword; private Integer count = 0; public Integer call() throws Exception { //call封装线程所需做的任务 if(search(file)) count ++; return count; } public boolean search(File file){ boolean founded = false; try(Scanner scanner = new Scanner(new FileInputStream(file))){ while(!founded && scanner.hasNextLine()){ if (scanner.nextLine().contains(keyword)) founded = true; } } catch (FileNotFoundException e) { e.printStackTrace(); } return founded; } }
标签:task cal down tst one 实现类 call() sys 实现
原文地址:https://www.cnblogs.com/jason111/p/8931127.html