Java基础--多线程4

来源:互联网 发布:老郎酒淘宝店 编辑:程序博客网 时间:2024/05/02 00:17

1.Callable、Future与FutureTask

Callable位于java.util.concurrent包下,它也是一个接口,在它里面也只声明了一个call方法。

public interface Callable<V> {    <span style="color:#ff0000;">V</span> call() throws Exception;}
类型参数是返回值的类型。

Future保存异步计算的结果。就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果。必要时可以通过get方法获取执行结果,该方法会阻塞直到任务返回结果。

public interface Future<V> {    boolean cancel(boolean mayInterruptIfRunning);<span style="white-space:pre"></span>//取消计算    boolean isCancelled();<span style="white-space:pre"></span>//检测是否取消    boolean isDone();<span style="white-space:pre"></span>//检测任务是否完成    V get() throws InterruptedException, ExecutionException;   //被阻塞,知道计算完成    V get(long timeout, TimeUnit unit)<span style="white-space:pre"></span>//调用超时会抛出InterruptedException,如果计算完成,get方法立即返回        throws InterruptedException, ExecutionException, TimeoutException;}
FutureTask类实现了RunnableFuture接口,RunnableFuture继承了Runnable接口和Future接口,所以FutureTask可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值。FutureTask的两个构造器

public FutureTask(Callable<V> callable) {}public FutureTask(Runnable runnable, V result) {}
示例:

public static void main(String[] args) {Scanner console = new Scanner(System.in);System.out.print("Enter Base Directory(E:/)");String directory = console.nextLine();System.out.print("Enter the Key words");String keyword = console.nextLine();MachCounter counter = new MachCounter(new File(directory), keyword);FutureTask<Integer> task = new FutureTask<>(counter);Thread t = new Thread(task);t.start();try {System.out.println(task.get() + "matching files");} catch (InterruptedException | ExecutionException e) {e.printStackTrace();}}}

public class MachCounter implements Callable<Integer> {private File directory;private String keyword;private int count;public MachCounter(File directory, String keyword) {this.directory = directory;this.keyword = keyword;}@Overridepublic Integer call() throws Exception {count = 0;try {File[] files = directory.listFiles();List<Future<Integer>> results = new ArrayList<>();for (File file : files) {if (file.isDirectory()) {MachCounter counter = new MachCounter(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> result : results) {count += result.get();}} catch (InterruptedException e) {e.getStackTrace();}return count;}private boolean search(File file) {try (Scanner in = new Scanner(file)) {boolean found = false;while (!found && in.hasNextLine()) {String line = in.nextLine();if (line.contains(keyword)) {found = true;}}return found;} catch (IOException e) {return false;}}}

2.执行器(Executor)

ExecutorService executor = Executors.newCachedThreadPool();MachCounter counter = new MachCounter(new File(directory), keyword,executor);Future<Integer> result = executor.submit(counter);
使用连接池步骤:

1)调用Executors类的静态方法newCachedThreadPool或newFixedThreadPool

2)调用submit方法提交Runnable或Collable对象

3)保存好返回的Future对象

4)不提交任何任务时候,调用shutdown

预定执行

 ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);        executor.scheduleAtFixedRate(new ScheduleTime(), Integer.parseInt(startTime),            Integer.parseInt(scanTime), TimeUnit.MILLISECONDS);

















0 0