zoukankan      html  css  js  c++  java
  • 创建线程的方式四:使用线程池

    package com.atguigu.java2;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ThreadPoolExecutor;
    
    /**
     * 创建线程的方式四:使用线程池
     *
     * 好处:
     * 1.提高响应速度(减少了创建新线程的时间)
     * 2.降低资源消耗(重复利用线程池中线程,不需要每次都创建)
     * 3.便于线程管理
     *      corePoolSize:核心池的大小
     *      maximumPoolSize:最大线程数
     *      keepAliveTime:线程没有任务时最多保持多长时间后会终止
     *
     *
     * 面试题:创建多线程有几种方式?四种!
     * @author shkstart
     * @create 2019-02-15 下午 6:30
     */
    
    class NumberThread implements Runnable{
    
        @Override
        public void run() {
            for(int i = 0;i <= 100;i++){
                if(i % 2 == 0){
                    System.out.println(Thread.currentThread().getName() + ": " + i);
                }
            }
        }
    }
    
    class NumberThread1 implements Runnable{
    
        @Override
        public void run() {
            for(int i = 0;i <= 100;i++){
                if(i % 2 != 0){
                    System.out.println(Thread.currentThread().getName() + ": " + i);
                }
            }
        }
    }
    
    public class ThreadPool {
    
        public static void main(String[] args) {
            //1. 提供指定线程数量的线程池
            ExecutorService service = Executors.newFixedThreadPool(10);
            ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;
            //设置线程池的属性
    //        System.out.println(service.getClass());
    //        service1.setCorePoolSize(15);
    //        service1.setKeepAliveTime();
    
    
            //2.执行指定的线程的操作。需要提供实现Runnable接口或Callable接口实现类的对象
            service.execute(new NumberThread());//适合适用于Runnable
            service.execute(new NumberThread1());//适合适用于Runnable
    
    //        service.submit(Callable callable);//适合使用于Callable
            //3.关闭连接池
            service.shutdown();
        }
    
    }
    
    
  • 相关阅读:
    ajax专题
    luogu P1346 电车 最短路
    luogu P1462 通往奥格瑞玛的道路 最短路
    luogu P1328 生活大爆炸版石头剪刀布
    luogu P1315 联合权值 枚举
    luogu P1156 垃圾陷阱 背包问题
    luogu P1217 回文质数 枚举
    luogu P3650 滑雪课程设计 枚举
    luogu1209 修理牛棚 贪心
    luogu P1223 排队接水 贪心
  • 原文地址:https://www.cnblogs.com/fenxiangyuan/p/14418006.html
Copyright © 2011-2022 走看看