原創:轉載需注明原創地址 https://www.cnblogs.com/fanerwei222/p/11871727.html
Java線程--Callable使用
Callable和Runnable使用差不多, 但是Callable有返回值, 可以用Future接收. 看代碼:
public static void main(String[] args) { Callable callable = new Callable() { @Override public Object call() throws Exception { return "this is Callable's message"; } }; /** * 將callable丟進任務里面 */ FutureTask futureTask = new FutureTask(callable); /** * 啟動線程, 執行任務 */ new Thread(futureTask).start(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } try { System.out.println("執行任務后的結果: " + futureTask.get()); } catch (ExecutionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }
打印如下:
執行任務后的結果: this is Callable's message