java 线程池使用 Runnable&Callable&Future javathreadrunnablecallablefuture
程序员文章站
2022-04-03 12:38:29
...
1. 创建线程池
ExecutorService executorService = Executors.newCachedThreadPool();
2. 执行一次线程,调用Runnable接口实现
Future<?> future = executorService.submit(new DefaultRunnable()); System.out.println(future.get());
当线程池执行Runnable后,返回的Future.get()总是null
DefaultRunnable代码如下:
package threadpool; public class DefaultRunnable implements Runnable { private int count = 1; @Override public void run() { System.out.println("the count in default runnable is ["+count+++"]"); } }
3. 执行一次线程,调用Callable接口实现
Future<?> future = executorService.submit(new DefaultCallable()); System.out.println(future.get());
当线程池执行Callable时,返回的Future.get() 会返回Callable的返回值
DefaultCallable代码如下:
package threadpool; import java.util.concurrent.Callable; public class DefaultCallable implements Callable<Object> { private int count =1; @Override public Object call() throws Exception { return count++; } }
4. 关闭线程池
executorService.shutdown();