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示例如下:
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
以上就是小編今天的分享了,希望可以幫助到大家。