我们可能在某些特殊的需求下需要返回一个线程执行的结果,在java 1.5提供了Callable和Futrue就能帮你实现!不解释看代码
package cn.kge.com; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Demo2 { public static void main(String[] args) { ExecutorService threadPool = Executors.newSingleThreadExecutor(); Future<String> future = threadPool.submit(new Callable<String>() { public String call(){ String str = "hello"; try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return str+"world"; } }); try { System.out.println("执行结果:"+future.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }
执行结果:helloworld
时间: 2024-11-10 23:28:17