Java多线程之Callable接口的实现

2025-05-29 0 52

1.接口的定义:

?

1

2

3

4
public interface callable<v>

{

v call() throws exception;

}

2.callable和runnable的异同

先看下runnable接口的定义

?

1

2

3
public interface runnable {

public abstract void run();

}

callable的call()方法类似于runnable接口中run()方法,都定义任务要完成的工作,实现这两个接口时要分别重写这两个方法,主要的不同之处是call()方法是有返回值的(其实还有一些区别,例如call方法可以抛出异常,run方法不可以),运行callable任务可以拿到一个future对象,表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。通过future对象可以了解任务执行情况,可取消任务的执行,还可获取执行结果。

3. callable类型的任务可以有两种执行方式:

我们先定义一个callable任务mycallabletask:

?

1

2

3

4

5

6

7

8

9

10

11
class mycallabletask implements callable<integer>{

@override

public integer call() throws exception {

system.out.println("线程在进行计算");

thread.sleep(3000);

int sum = 0;

for(int i=0;i<100;i++)

sum += i;

return sum;

}

}

①借助futuretask执行

futuretask类同时实现了两个接口,future和runnable接口,所以它既可以作为runnable被线程执行,又可以作为future得到callable的返回值。

借助futuretask执行的大体流程是:

?

1

2

3
callable<integer> mycallabletask = new mycallabletask();

futuretask<integer> futuretask= new futuretask<integer>(mycallabletask);

new thread(futuretask).start();

通过futuretask可以得到mycallabletask的call()的运行结果: futuretask.get();

②借助线程池来运行

线程池中执行callable任务的原型例如:

?

1

2

3

4

5

6

7
public interface executorservice extends executor {

//提交一个callable任务,返回值为一个future类型

<t> future<t> submit(callable<t> task);

//other methods...

}

借助线程池来运行callable任务的一般流程为:

?

1

2
executorservice exec = executors.newcachedthreadpool();

future<integer> future = exec.submit(new mycallabletask());

通过future可以得到mycallabletask的call()的运行结果: future.get();

在网上看到了几个比较好的代码例子:

a.callable任务借助futuretask运行:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19
public class callableandfuturetask {

public static void main(string[] args) {

callable<integer> callable = new callable<integer>() {

public integer call() throws exception {

return new random().nextint(100);

}

};

futuretask<integer> future = new futuretask<integer>(callable);

new thread(future).start();

try {

thread.sleep(5000);

system.out.println(future.get());

} catch (interruptedexception e) {

e.printstacktrace();

} catch (executionexception e) {

e.printstacktrace();

}

}

}

b.callable任务和线程池一起使用,然后返回值是future:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18
public class callableandfuture {

public static void main(string[] args) {

executorservice threadpool = executors.newsinglethreadexecutor();

future<integer> future = threadpool.submit(new callable<integer>() {

public integer call() throws exception {

return new random().nextint(100);

}

});

try {

thread.sleep(5000);// 可能做一些事情

system.out.println(future.get());

} catch (interruptedexception e) {

e.printstacktrace();

} catch (executionexception e) {

e.printstacktrace();

}

}

}

c.当执行多个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
class mycallabletask implements callable<string> {

private int id;

public onetask(int id){

this.id = id;

}

@override

public string call() throws exception {

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

system.out.println("thread"+ id);

thread.sleep(1000);

}

return "result of callable: "+id;

}

}

public class test {

public static void main(string[] args) {

//callable<string> mycallabletask = new mycallabletask(1);

executorservice exec = executors.newcachedthreadpool();

arraylist<future<string>> results = new arraylist<future<string>>();

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

results.add(exec.submit(new mycallabletask(i)));

}

for (future<string> fs : results) {

if (fs.isdone()) {

try {

system.out.println(fs.get());

} catch (exception e) {

e.printstacktrace();

}

} else {

system.out.println("mycallabletask任务未完成!");

}

}

exec.shutdown();

}

}

那么引入callable接口具有哪些好处呢?

①可以获得任务执行返回值;

②通过与future的结合,可以实现利用future来跟踪异步计算的结果。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:https://blog.csdn.net/sunp823/article/details/51569314

收藏 (0) 打赏

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

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

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

快网idc优惠网 建站教程 Java多线程之Callable接口的实现 https://www.kuaiidc.com/111428.html

相关文章

发表评论
暂无评论