java多线程之Future和FutureTask使用实例

2025-05-29 0 87

Executor框架使用Runnable 作为其基本的任务表示形式。Runnable是一种有局限性的抽象,然后可以写入日志,或者共享的数据结构,但是他不能返回一个值。

许多任务实际上都是存在延迟计算的:执行数据库查询,从网络上获取资源,或者某个复杂耗时的计算。对于这种任务,Callable是一个更好的抽象,他能返回一个值,并可能抛出一个异常。Future表示一个任务的周期,并提供了相应的方法来判断是否已经完成或者取消,以及获取任务的结果和取消任务。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75
public interface Callable<V> { /** * Computes a result, or throws an exception if unable to do so. * * @return computed result * @throws Exception if unable to compute a result */ V call() throws Exception; }

public interface Future<V> {

/**

* Attempts to cancel execution of this task. This attempt will

* fail if the task has already completed, has already been cancelled,

* or could not be cancelled for some other reason. If successful,

* and this task has not started when <tt>cancel</tt> is called,

* this task should never run. If the task has already started,

* then the <tt>mayInterruptIfRunning</tt> parameter determines

* whether the thread executing this task should be interrupted in

* an attempt to stop the task.

*

* <p>After this method returns, subsequent calls to {@link #isDone} will

* always return <tt>true</tt>. Subsequent calls to {@link #isCancelled}

* will always return <tt>true</tt> if this method returned <tt>true</tt>.

*

* @param mayInterruptIfRunning <tt>true</tt> if the thread executing this

* task should be interrupted; otherwise, in-progress tasks are allowed

* to complete

* @return <tt>false</tt> if the task could not be cancelled,

* typically because it has already completed normally;

* <tt>true</tt> otherwise

*/

boolean cancel(boolean mayInterruptIfRunning);

/**

* Returns <tt>true</tt> if this task was cancelled before it completed

* normally.

*

* @return <tt>true</tt> if this task was cancelled before it completed

*/

boolean isCancelled();

/**

* Returns <tt>true</tt> if this task completed.

*

* Completion may be due to normal termination, an exception, or

* cancellation -- in all of these cases, this method will return

* <tt>true</tt>.

*

* @return <tt>true</tt> if this task completed

*/

boolean isDone();

/**

* Waits if necessary for the computation to complete, and then

* retrieves its result.

*

* @return the computed result

* @throws CancellationException if the computation was cancelled

* @throws ExecutionException if the computation threw an

* exception

* @throws InterruptedException if the current thread was interrupted

* while waiting

*/

V get() throws InterruptedException, ExecutionException;

/**

* Waits if necessary for at most the given time for the computation

* to complete, and then retrieves its result, if available.

*

* @param timeout the maximum time to wait

* @param unit the time unit of the timeout argument

* @return the computed result

* @throws CancellationException if the computation was cancelled

* @throws ExecutionException if the computation threw an

* exception

* @throws InterruptedException if the current thread was interrupted

* while waiting

* @throws TimeoutException if the wait timed out

*/

V get(long timeout, TimeUnit unit)

throws InterruptedException, ExecutionException, TimeoutException;

}

可以通过多种方法来创建一个Future来描述任务。ExecutorService中的submit方法接受一个Runnable或者Callable,然后返回一个Future来获得任务的执行结果或者取消任务。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50
/**

* Submits a value-returning task for execution and returns a

* Future representing the pending results of the task. The

* Future's <tt>get</tt> method will return the task's result upon

* successful completion.

*

* <p>

* If you would like to immediately block waiting

* for a task, you can use constructions of the form

* <tt>result = exec.submit(aCallable).get();</tt>

*

* <p> Note: The {@link Executors} class includes a set of methods

* that can convert some other common closure-like objects,

* for example, {@link java.security.PrivilegedAction} to

* {@link Callable} form so they can be submitted.

*

* @param task the task to submit

* @return a Future representing pending completion of the task

* @throws RejectedExecutionException if the task cannot be

* scheduled for execution

* @throws NullPointerException if the task is null

*/

<T> Future<T> submit(Callable<T> task);

/**

* Submits a Runnable task for execution and returns a Future

* representing that task. The Future's <tt>get</tt> method will

* return the given result upon successful completion.

*

* @param task the task to submit

* @param result the result to return

* @return a Future representing pending completion of the task

* @throws RejectedExecutionException if the task cannot be

* scheduled for execution

* @throws NullPointerException if the task is null

*/

<T> Future<T> submit(Runnable task, T result);

/**

* Submits a Runnable task for execution and returns a Future

* representing that task. The Future's <tt>get</tt> method will

* return <tt>null</tt> upon <em>successful</em> completion.

*

* @param task the task to submit

* @return a Future representing pending completion of the task

* @throws RejectedExecutionException if the task cannot be

* scheduled for execution

* @throws NullPointerException if the task is null

*/

Future<?> submit(Runnable task);

另外ThreadPoolExecutor中的newTaskFor(Callable<T> task) 可以返回一个FutureTask。

假设我们通过一个方法从远程获取一些计算结果,假设方法是 List getDataFromRemote(),如果采用同步的方法,代码大概是 List data = getDataFromRemote(),我们将一直等待getDataFromRemote返回,然后才能继续后面的工作,这个函数是从远程获取计算结果的,如果需要很长时间,后面的代码又和这个数据没有什么关系的话,阻塞在那里就会浪费很多时间。我们有什么办法可以改进呢???

能够想到的办法是调用函数后,立即返回,然后继续执行,等需要用数据的时候,再取或者等待这个数据。具体实现有两种方式,一个是用Future,另一个是回调。

?

1

2

3
Future<List> future = getDataFromRemoteByFuture();

//do something....

List data = future.get();

可以看到我们返回的是一个Future对象,然后接着自己的处理后面通过future.get()来获得我们想要的值。也就是说在执行getDataFromRemoteByFuture的时候,就已经启动了对远程计算结果的获取,同时自己的线程还继续执行不阻塞。知道获取时候再拿数据就可以。看一下getDataFromRemoteByFuture的实现:

?

1

2

3

4

5

6

7

8

9
private Future<List> getDataFromRemoteByFuture() {

return threadPool.submit(new Callable<List>() {

@Override

public List call() throws Exception {

return getDataFromRemote();

}

});

}

我们在这个方法中调用getDataFromRemote方法,并且用到了线程池。把任务加入线程池之后,理解返回Future对象。Future的get方法,还可以传入一个超时参数,用来设置等待时间,不会一直等下去。

也可以利用FutureTask来获取结果:

?

1

2

3

4

5

6

7

8

9
FutureTask<List> futureTask = new FutureTask<List>(new Callable<List>() {

@Override

public List call() throws Exception {

return getDataFromRemote();

}

});

threadPool.submit(futureTask);

futureTask.get();

FutureTask是一个具体的实现类,ThreadPoolExecutor的submit方法返回的就是一个Future的实现,这个实现就是FutureTask的一个具体实例,FutureTask帮助实现了具体的任务执行,以及和Future接口中的get方法的关联。

FutureTask除了帮助ThreadPool很好的实现了对加入线程池任务的Future支持外,也为我们提供了很大的便利,使得我们自己也可以实现支持Future的任务调度。

补充知识:多线程中Future与FutureTask的区别和联系

线程的创建方式中有两种,一种是实现Runnable接口,另一种是继承Thread,但是这两种方式都有个缺点,那就是在任务执行完成之后无法获取返回结果,于是就有了Callable接口,Future接口与FutureTask类的配和取得返回的结果。

我们先回顾一下java.lang.Runnable接口,就声明了run(),其返回值为void,当然就无法获取结果。

?

1

2

3
public interface Runnable {

public abstract void run();

}

而Callable的接口定义如下

?

1

2

3
public interface Callable<V> {

V call() throws Exception;

}

该接口声明了一个名称为call()的方法,同时这个方法可以有返回值V,也可以抛出异常。嗯,对该接口我们先了解这么多就行,下面我们来说明如何使用,前篇文章我们说过,无论是Runnable接口的实现类还是Callable接口的实现类,都可以被ThreadPoolExecutor或ScheduledThreadPoolExecutor执行,ThreadPoolExecutor或ScheduledThreadPoolExecutor都实现了ExcutorService接口,而因此Callable需要和Executor框架中的ExcutorService结合使用,我们先看看ExecutorService提供的方法:

?

1

2

3
<T> Future<T> submit(Callable<T> task);

<T> Future<T> submit(Runnable task, T result);

Future<?> submit(Runnable task);

第一个方法:submit提交一个实现Callable接口的任务,并且返回封装了异步计算结果的Future。

第二个方法:submit提交一个实现Runnable接口的任务,并且指定了在调用Future的get方法时返回的result对象。(不常用)

第三个方法:submit提交一个实现Runnable接口的任务,并且返回封装了异步计算结果的Future。

因此我们只要创建好我们的线程对象(实现Callable接口或者Runnable接口),然后通过上面3个方法提交给线程池去执行即可。还有点要注意的是,除了我们自己实现Callable对象外,我们还可以使用工厂类Executors来把一个Runnable对象包装成Callable对象。Executors工厂类提供的方法如下:

public static Callable<Object> callable(Runnable task)

public static <T> Callable<T> callable(Runnable task, T result)

2.Future<V>接口

Future<V>接口是用来获取异步计算结果的,说白了就是对具体的Runnable或者Callable对象任务执行的结果进行获取(get()),取消(cancel()),判断是否完成等操作。我们看看Future接口的源码:

?

1

2

3

4

5

6

7
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;

}

方法解析:

V get() :获取异步执行的结果,如果没有结果可用,此方法会阻塞直到异步计算完成。

V get(Long timeout , TimeUnit unit) :获取异步执行结果,如果没有结果可用,此方法会阻塞,但是会有时间限制,如果阻塞时间超过设定的timeout时间,该方法将抛出异常。

boolean isDone() :如果任务执行结束,无论是正常结束或是中途取消还是发生异常,都返回true。

boolean isCanceller() :如果任务完成前被取消,则返回true。

boolean cancel(boolean mayInterruptRunning) :如果任务还没开始,执行cancel(…)方法将返回false;如果任务已经启动,执行cancel(true)方法将以中断执行此任务线程的方式来试图停止任务,如果停止成功,返回true;当任务已经启动,执行cancel(false)方法将不会对正在执行的任务线程产生影响(让线程正常执行到完成),此时返回false;当任务已经完成,执行cancel(…)方法将返回false。mayInterruptRunning参数表示是否中断执行中的线程。

通过方法分析我们也知道实际上Future提供了3种功能:(1)能够中断执行中的任务(2)判断任务是否执行完成(3)获取任务执行完成后额结果。

但是我们必须明白Future只是一个接口,我们无法直接创建对象,因此就需要其实现类FutureTask登场啦。

3.FutureTask类

我们先来看看FutureTask的实现

?

1

2

3

4

5
public class FutureTask<V> implements RunnableFuture<V> {

FutureTask类实现了RunnableFuture接口,我们看一下RunnableFuture接口的实现:

public interface RunnableFuture<V> extends Runnable, Future<V> {

void run();

}

分析:FutureTask除了实现了Future接口外还实现了Runnable接口(即可以通过Runnable接口实现线程,也可以通过Future取得线程执行完后的结果),因此FutureTask也可以直接提交给Executor执行。

最后我们给出FutureTask的两种构造函数:

?

1

2

3

4
public FutureTask(Callable<V> callable) {

}

public FutureTask(Runnable runnable, V result) {

}

4.Callable<V>/Future<V>/FutureTask的使用 (封装了异步获取结果的Future!!!)

通过上面的介绍,我们对Callable,Future,FutureTask都有了比较清晰的了解了,那么它们到底有什么用呢?我们前面说过通过这样的方式去创建线程的话,最大的好处就是能够返回结果,加入有这样的场景,我们现在需要计算一个数据,而这个数据的计算比较耗时,而我们后面的程序也要用到这个数据结果,那么这个时 Callable岂不是最好的选择?我们可以开设一个线程去执行计算,而主线程继续做其他事,而后面需要使用到这个数据时,我们再使用Future获取不就可以了吗?下面我们就来编写一个这样的实例

4.1 使用Callable+Future获取执行结果

Callable实现类如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22
package com.zejian.Executor;

import java.util.concurrent.Callable;

/**

* @author zejian

* @time 2016年3月15日 下午2:02:42

* @decrition Callable接口实例

*/

public class CallableDemo implements Callable<Integer> {

private int sum;

@Override

public Integer call() throws Exception {

System.out.println("Callable子线程开始计算啦!");

Thread.sleep(2000);

for(int i=0 ;i<5000;i++){

sum=sum+i;

}

System.out.println("Callable子线程计算结束!");

return sum;

}

}

Callable执行测试类如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38
package com.zejian.Executor;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;

/**

* @author zejian

* @time 2016年3月15日 下午2:05:43

* @decrition callable执行测试类

*/

public class CallableTest {

public static void main(String[] args) {

//创建线程池

ExecutorService es = Executors.newSingleThreadExecutor();

//创建Callable对象任务

CallableDemo calTask=new CallableDemo();

//提交任务并获取执行结果

Future<Integer> future =es.submit(calTask);

//关闭线程池

es.shutdown();

try {

Thread.sleep(2000);

System.out.println("主线程在执行其他任务");

if(future.get()!=null){

//输出获取到的结果

System.out.println("future.get()-->"+future.get());

}else{

//输出获取到的结果

System.out.println("future.get()未获取到结果");

}

} catch (Exception e) {

e.printStackTrace();

}

System.out.println("主线程在执行完成");

}

}

执行结果:

Callable子线程开始计算啦!

主线程在执行其他任务

Callable子线程计算结束!

future.get()–>12497500

主线程在执行完成

4.2 使用Callable+FutureTask获取执行结果

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50
package com.zejian.Executor;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;

import java.util.concurrent.FutureTask;

/**

* @author zejian

* @time 2016年3月15日 下午2:05:43

* @decrition callable执行测试类

*/

public class CallableTest {

public static void main(String[] args) {

// //创建线程池

// ExecutorService es = Executors.newSingleThreadExecutor();

// //创建Callable对象任务

// CallableDemo calTask=new CallableDemo();

// //提交任务并获取执行结果

// Future<Integer> future =es.submit(calTask);

// //关闭线程池

// es.shutdown();

//创建线程池

ExecutorService es = Executors.newSingleThreadExecutor();

//创建Callable对象任务

CallableDemo calTask=new CallableDemo();

//创建FutureTask

FutureTask<Integer> futureTask=new FutureTask<>(calTask);

//执行任务

es.submit(futureTask);

//关闭线程池

es.shutdown();

try {

Thread.sleep(2000);

System.out.println("主线程在执行其他任务");

if(futureTask.get()!=null){

//输出获取到的结果

System.out.println("futureTask.get()-->"+futureTask.get());

}else{

//输出获取到的结果

System.out.println("futureTask.get()未获取到结果");

}

} catch (Exception e) {

e.printStackTrace();

}

System.out.println("主线程在执行完成");

}

}

执行结果:

Callable子线程开始计算啦!

主线程在执行其他任务

Callable子线程计算结束!

futureTask.get()–>12497500

主线程在执行完成

以上这篇java多线程之Future和FutureTask使用实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持快网idc。

原文链接:https://blog.csdn.net/weixin_43469563/article/details/108830688

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 java多线程之Future和FutureTask使用实例 https://www.kuaiidc.com/116522.html

相关文章

发表评论
暂无评论