扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
8. Callables and Futures
实现多线程时一般用的是Runnable接口,但是他有一个问题就是他没有参数和返回值,所以当执行一个线程需要返回一个值的时候就不是很方便了。Callable接口和Runnable差不多,但是他提供了参数和返回值:
public interface Callable<V> { V call() throws Exception; } |
public interface Future<V> { V get() throws . . .; V get(long timeout, TimeUnit unit) throws . . .; void cancel(boolean mayInterrupt); boolean isCancelled(); boolean isDone(); } |
Callable<Integer> myComputation = . . .; FutureTask<Integer> task = new FutureTask<Integer>(myComputation); Thread t = new Thread(task); // it's a Runnable t.start(); . . . Integer result = task.get(); // it's a Future |
newCachedThreadPool New threads are created as needed; idle threads are kept for 60 seconds. newFixedThreadPool The pool contains a fixed set of threads; idle threads are kept indefinitely. newSingleThreadExecutor A "pool" with a single thread that executes the submitted tasks sequentially. newScheduledThreadPool A fixed-thread pool for scheduled execution. newSingleThreadScheduledExecutor A single-thread "pool" for scheduled execution. |
EventQueue.invokeLater(new Runnable() { public void run() { label.setText(percentage + "% complete"); } }); |
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。
现场直击|2021世界人工智能大会
直击5G创新地带,就在2021MWC上海
5G已至 转型当时——服务提供商如何把握转型的绝佳时机
寻找自己的Flag
华为开发者大会2020(Cloud)- 科技行者