服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Java多线程之Callable接口的实现

Java多线程之Callable接口的实现

2021-05-25 12:23sunp823 Java教程

这篇文章主要介绍了Java多线程之Callable接口的实现,Callable和Runnbale一样代表着任务,区别在于Callable有返回值并且可以抛出异常。感兴趣的小伙伴们可以参考一下

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来跟踪异步计算的结果。

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

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

延伸 · 阅读

精彩推荐