1.Runnablegit
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.應用github
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; } }