zoukankan      html  css  js  c++  java
  • Java Executors 类

    使用示例

    class RunnableThread implements Runnable {
        @Override
        public void run() {
            System.out.println("通过线程池方式创建的线程:" + Thread.currentThread().getName() + " ");
        }
    }
    
    public class Test {
        public static void main(String[] args) throws Exception{
            //一个定长线程池,可控制最大并发数,超出的线程会在队列中等待。
            ExecutorService executorService1 = Executors.newFixedThreadPool(5);
            //一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
            ExecutorService executorService2 = Executors.newCachedThreadPool();
            //一个单线程的线程池,用唯一的工作线程来执行任务,保证所有任务按照指定顺序。
            ExecutorService executorService3 = Executors.newSingleThreadExecutor();
            //一个定长线程池,支持定时及周期性任务执行。
            ExecutorService executorService4 = Executors.newScheduledThreadPool(3);
    
            for(int i = 0; i<3; i++)
            {
                RunnableThread thread = new RunnableThread();
                executorService1.execute(thread);
            }
            //关闭线程池
            executorService1.shutdown();
            executorService2.shutdown();
            executorService3.shutdown();
            executorService4.shutdown();
        }
    }
    
    结果:
    通过线程池方式创建的线程:pool-1-thread-1 
    通过线程池方式创建的线程:pool-1-thread-2 
    通过线程池方式创建的线程:pool-1-thread-3
    
  • 相关阅读:
    python网络编程,requests模块
    python操作excel
    python加密模块hashlib
    python操作redis
    python操作mysql
    python常用模块3(os和sys模块)
    python打开网站
    python常用模块2
    python模块简介
    mac下开发——环境心得(杂项,持续性更新)
  • 原文地址:https://www.cnblogs.com/feiqiangsheng/p/15328849.html
Copyright © 2011-2022 走看看