标签:创建 ret inf override style 重复 cut 部分 tin
线程池提供一个线程队列,队列中保存着所有等待状态的线程。避免了创建与销毁等额外开销,提交了响应的速度。
Java线程池相关的接口和类均在 java.util.concurrent 包下,其相关关系(部分)如下
1-Executors类简介:简单的说是线程方法的工具类,提供了 创建线程池等方法。
2-ExecutorService 类创建线程池
//创建缓存线程池,线程数量不固定,可以自动调节线程数量 ExecutorService executor1 = Executors.newCachedThreadPool(); //创建缓存线程池,并且只有一个线程数量 ExecutorService executor2 = Executors.newSingleThreadExecutor(); //创建缓存线程池,并指定线程数量 ExecutorService executor3 = Executors.newFixedThreadPool(5);
3-ExecutorService 类执行线程
public class ThreadPoolTest { public static void main(String[] args) throws ExecutionException, InterruptedException { //创建线程池 ExecutorService executor = Executors.newFixedThreadPool(5); //方法1:Future<?> submit(Runnable task); executor.submit(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName() + " runnable"); } }); //方法2:<T> Future<T> submit(Callable<T> task); Future<Object> future = executor.submit(new Callable<Object>() { @Override public Object call() throws Exception { System.out.println(Thread.currentThread().getName() + " callable"); return new Random().nextInt(100); } }); System.out.println(future.get()); //关闭线程池。ExecutorService executor.shutdown(); } }
4-ScheduledExecutorService 使用
public class ThreadPoolTest { public static void main(String[] args) throws ExecutionException, InterruptedException { //1-创建线程池 ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(5); //2-执行线程,延迟2秒执行 for(int i=0; i<10; i++){ scheduledExecutor.schedule(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()); } },2,TimeUnit.SECONDS ); } //3-关闭线程池 scheduledExecutor.shutdown(); } } ------------------------------日志输出------------------------------ pool-1-thread-1 pool-1-thread-1 pool-1-thread-1 pool-1-thread-1 pool-1-thread-3 pool-1-thread-3 pool-1-thread-5 pool-1-thread-2 pool-1-thread-4 pool-1-thread-1 //日志说明:线程只有5个,并且会重复使用
END
标签:创建 ret inf override style 重复 cut 部分 tin
原文地址:https://www.cnblogs.com/wobuchifanqie/p/12546995.html