callable - java

来源:趣味经验馆 1.77W

<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>

callable java是什么,让我们一起了解一下?

IDL作为动态链接库被外部程序调用的技术,使用Callable 技术,外部程序可以像IDL命令行一样使用IDL命令或调用执行IDL的程序。

那么,在实际操作中,callable的使用方法是什么?

1、Callable 使用 call() 方法。

2、call() 可以返回值。
3、call() 可以抛出受检查的异常,比如ClassNotFoundException。

callable java

Callable示例如下:  

class TaskWithResult implements Callable<String> {      private int id;        public TaskWithResult(int id) {          this.id = id;      }        @Override      public String call() throws Exception {          return "result of TaskWithResult " + id;      }  }    public class CallableTest {      public static void main(String[] args) throws InterruptedException,              ExecutionException {          ExecutorService exec = Executors.newCachedThreadPool();          ArrayList<Future<String>> results = new ArrayList<Future<String>>();    //Future 相当于是用来存放Executor执行的结果的一种容器          for (int i = 0; i < 10; i++) {              results.add(exec.submit(new TaskWithResult(i)));          }          for (Future<String> fs : results) {              if (fs.isDone()) {                  System.out.println(fs.get());              } else {                  System.out.println("Future result is not yet complete");              }          }          exec.shutdown();      }  }

执行结果:

result of TaskWithResult 0  result of TaskWithResult 1  result of TaskWithResult 2  result of TaskWithResult 3  result of TaskWithResult 4  result of TaskWithResult 5  result of TaskWithResult 6  result of TaskWithResult 7  result of TaskWithResult 8  result of TaskWithResult 9

以上就是小编今天的分享了,希望可以帮助到大家。

热门标签