原创:转载需注明原创地址 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