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
- Java基础--多线程4
- Java基础/Java多线程
- Java基础-多线程基础篇
- java多线程基础
- Java多线程编程基础
- java多线程开发基础
- Java多线程基础
- Java -- 多线程技术基础
- 【java】多线程基础
- Java基础:多线程
- Java语言基础:多线程
- Java语言基础:多线程
- Java语言基础:多线程
- java多线程基础分析
- Java多线程编程基础
- java 多线程基础
- Java基础_多线程
- Java多线程基础
- Android 有道词典的简单实现方法介绍
- Android Studio 常用功能介绍
- 关于 i++和++i 以及for循环
- opencv avi视频播放带进度条
- git服务器在linux搭建在window下提交
- Java基础--多线程4
- 模拟带Servlet技术的HTTP服务器的Java实现
- log4j的用法
- Activity 和 intent FLAG 集合
- 使用API进行发运确认并运行Interface Trip Stop
- DCE打印路由时某种情况下的gdb结果
- android学习笔记四——Service
- 性能均衡实用 Thinkpad E450-2CD热卖
- 技术演绎之 [ java ] 程序解析