Callable & Future

来源:互联网 发布:linux默认root密码 编辑:程序博客网 时间:2024/06/07 09:51

我们知道创建一个线程可以通过实现Runnable接口和继承Thread类,并重写run方法。但是run方法是不带返回的。

而Callable接口同样是用于多线程,并能返回一个Future

ExecutorService exe = Executors.newFixedThreadPool(2);Future<String> future =exe.submit(new Callable<String>() {//submit返回Future@Overridepublic String call() throws Exception {Thread.sleep(10000);return "hello";}});try {System.out.println("return data="+future.get());//get return data from Future.//System.out.println(future.get(2, TimeUnit.SECONDS));// set timeout to get return data. if timeout, TimeoutException thrown} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}



0 0
原创粉丝点击