Callable和Future

xiaoxiao2021-02-28  129

Callable启动线程,它可以有返回值,可以通过future.get()方法来获取线程的执行结果

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(1000);// 可能做一些事情 System.out.println(future.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }
转载请注明原文地址: https://www.6miu.com/read-23768.html

最新回复(0)