java Callable Future
2016-06-01 16:36
363 查看
@FunctionalInterface public interface Runnable { public abstract void run(); } @FunctionalInterface public interface Callable<V> { V call() throws Exception; } <pre name="code" class="java">public interface Future<V> {boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
public interface RunnableFuture<V> extends Runnable, Future<V> {
/**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
void run();
}
package com.provider.future;
import java.util.Random;
import java.util.concurrent.Callable;
public class Task implements Callable<Integer>{
public Integer call() throws Exception {
Thread.sleep(10000);
Random r = new Random();
return r.nextInt(1000);
}
}
package com.provider.future; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; public class TestFu { public void fun1(){ ExecutorService executorService = Executors.newFixedThreadPool(2); Future<Integ b7c9 er> submit = executorService.submit(new Task()); executorService.shutdown(); System.out.println(submit.isDone()); try { Thread.sleep(1500); System.out.println(submit.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } public void fun2(){ ExecutorService executorService = Executors.newFixedThreadPool(2); FutureTask<Integer> ft = new FutureTask<Integer>(new Task()); executorService.submit(ft); executorService.shutdown(); System.out.println(ft.isDone()); try { Thread.sleep(1500); System.out.println(ft.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } public static void main(String[] args) { TestFu testFu =new TestFu(); testFu.fun1(); testFu.fun2(); } }
相关文章推荐
- 如何从action传递参数到struts配置文件
- java传值和传引用
- Spring加载Properties配置文件的加密解密处理
- [LeetCode][2]Add Two Numbers解析 -Java实现
- Spring AOP
- Java Exception in thread "main" java.lang.NoClassDefFoundError问题
- Spring配置文件浅析(学习笔记)
- java并发编程——性能和扩展性
- java常见算法题目
- Java读写文件方法总结
- java读取远程url图片并获取图片宽高
- 数据库框架Realm Java
- [LeetCode][1]Two Sum解析 -Java实现
- hibernate中的java对象有几种状态,其相互关系如何(区别和相互转换)
- java记事本1.2版
- (Java)LeetCode-22. Generate Parentheses
- java正则表达式相关类的使用
- 初识java.util.concurrent.CyclicBarrier
- java集合类说明与区别
- Java Collections Framework Java集合框架概览