在过去的几篇文章中,我们学到了很多关于 Java 线条(/community/tutorials/multithreading-in-java Java Thread Tutorial
)但有时我们希望一个线条能够返回我们可以使用的某种价值。
Java 可调用
Java Callable interface use Generic to define the return type of Object. Executors class provide useful methods to execute Java Callable in a thread pool. Since callable tasks run in parallel, we have to wait for the returned Object.
Java 未来
Java 可召回任务返回 java.util.concurrent.Future 对象. 使用 Java Future 对象,我们可以找出可召回任务的状态并获得返回的对象。 它提供了 get() 方法,可以等到可召回完成,然后返回结果。 Java Future 提供了 cancel() 方法来取消相关可召回任务。 有一个过载版本的 get() 方法,我们可以指定等待结果的时间,这是有用的,以避免当前的线程被封锁更长时间。 有 isDone() 和 isCancelled() 方法来找出相关的可召回任务的当前状态。 这里是一个简单的例子,Java 可召唤任务返回执行任务的名称一秒后。 我们正在使用 [Executor
1package com.journaldev.threads;
2
3import java.util.ArrayList;
4import java.util.Date;
5import java.util.List;
6import java.util.concurrent.Callable;
7import java.util.concurrent.ExecutionException;
8import java.util.concurrent.ExecutorService;
9import java.util.concurrent.Executors;
10import java.util.concurrent.Future;
11
12public class MyCallable implements Callable<String> {
13
14 @Override
15 public String call() throws Exception {
16 Thread.sleep(1000);
17 //return the thread name executing this callable task
18 return Thread.currentThread().getName();
19 }
20
21 public static void main(String args[]){
22 //Get ExecutorService from Executors utility class, thread pool size is 10
23 ExecutorService executor = Executors.newFixedThreadPool(10);
24 //create a list to hold the Future object associated with Callable
25 List<Future<String>> list = new ArrayList<Future<String>>();
26 //Create MyCallable instance
27 Callable<String> callable = new MyCallable();
28 for(int i=0; i< 100; i++){
29 //submit Callable tasks to be executed by thread pool
30 Future<String> future = executor.submit(callable);
31 //add Future to the list, we can get return value using Future
32 list.add(future);
33 }
34 for(Future<String> fut : list){
35 try {
36 //print the return value of Future, notice the output delay in console
37 // because Future.get() waits for task to get completed
38 System.out.println(new Date()+ "::"+fut.get());
39 } catch (InterruptedException | ExecutionException e) {
40 e.printStackTrace();
41 }
42 }
43 //shut down the executor service now
44 executor.shutdown();
45 }
46
47}
一旦我们运行上述程序,你会注意到输出的延迟,因为java Future get()方法等待Java可调用任务完成。
1Mon Dec 31 20:40:15 PST 2012::pool-1-thread-1
2Mon Dec 31 20:40:16 PST 2012::pool-1-thread-2
3Mon Dec 31 20:40:16 PST 2012::pool-1-thread-3
4Mon Dec 31 20:40:16 PST 2012::pool-1-thread-4
5Mon Dec 31 20:40:16 PST 2012::pool-1-thread-5
6Mon Dec 31 20:40:16 PST 2012::pool-1-thread-6
7Mon Dec 31 20:40:16 PST 2012::pool-1-thread-7
8Mon Dec 31 20:40:16 PST 2012::pool-1-thread-8
9Mon Dec 31 20:40:16 PST 2012::pool-1-thread-9
10Mon Dec 31 20:40:16 PST 2012::pool-1-thread-10
11Mon Dec 31 20:40:16 PST 2012::pool-1-thread-2
12...
** 提示**:如果我们想忽略一些 Java Future 接口的方法,例如忽略 get()
方法以在某些默认时间之后过时,而不是等待无限期,那么在这种情况下 ** Java FutureTask** 类是有用的,即是未来接口的基本实现。