zoukankan      html  css  js  c++  java
  • Java多线程与并发库高级应用-线程池

    线程池

    线程池的思想

      

     线程池的概念与Executors类的应用

      > 创建固定大小的线程池

      > 创建缓存线程池

      > 创建单一线程池(如何实现线程死掉后重新启动?)

    关闭线程池

      > shutdown 与 shutdownNow的比较

    用线程池启动定时器

      > 调用ScheduleExecutorService 的 schedule 方法,返回的ScheduleFuture对象可以取消任务。

      > 支持间隔重复任务的定时方式,不直接支持决定定时的方法,需要转换成相对时间方式。

      

    public class ThreadPoolTest {
    
        public static void main(String[] args) {
    //        ExecutorService threadPool = Executors.newFixedThreadPool(3); //创建一个固定大小的线程池,线程池中有3个线程可以同时服务
            //缓存线程池 线程池中的线程数是动态变化的,当所有线程处于服务状态时,还有需要被服务的任务,自动增加一个线程进行服务
            //当任务执行完毕,线程处于空闲一段时间,超时后则自动回收销毁线程
    //        ExecutorService threadPool = Executors.newCachedThreadPool();  
            //创建一个只有一个线程的线程池,当这个线程挂掉时,可以自动生成一个线程来代替
            //可以解决一个网上很多人问的问题(如何实现线程死掉后重新启动?)
            ExecutorService threadPool = Executors.newSingleThreadExecutor();   
            for(int i = 0;i<10;i++){  //往线程池中扔10个任务
                final int task = i;
                threadPool.execute(new Runnable() {  //往线程池中扔了一个任务
                    
                    @Override
                    public void run() {
                        for(int j = 0;j<10;j++){
                            System.out.println(Thread.currentThread().getName()+" is loop of "+ j + "the task of "+task);
                        }
                    }
                });
            }
            System.out.println("all of 10 tasks have committed");
            //上述代码执行完后 没有结束,线程池中有3个线程一直存在,所以程序不会结束
            //可以使用 threadPool.shutdown()
            threadPool.shutdown();  //当线程池中线程执行完所有任务,所有线程处于空闲状态时,干掉所有线程,程序自结束
    //        threadPool.shutdownNow();  //立即把池子中所有线程干掉,无论任务是否干完
            
        }
    }
    package com.java.juc;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    /**
     * 一、线程池:提供了一个线程队列,队列中保存着所有等待状态的线程。避免了创建与销毁额外的开销,提高了响应的速度。
     * 
     * 二、线程池的体系结构:
     *     java.util.concurrent.Executor: 负责线程的使用与调度根接口。
     *         |--**ExecutorService 子接口:线程池的主要接口
     *             |--ThreadPoolExecutor 线程池的实现类
     *             |--ScheduledExecutorService 子接口:负责线程的调度
     *                 |--ScheduledThreadPoolExecutor : 继承 ThreadPoolExecutor 实现ScheduledExecutorService
     * 三、工具类:Executors
     *     ExecutorService newFixedThreadPool() :创建固定大小的线程池。
     *     ExecutorService newCachedThreadPool(): 创建无限大小的线程池,线程池中线程数量不固定,可根据需求自动更改。
     *     ExecutorService newSingleThreadPool() : 创建单个线程池,线程池中只有一个线程。
     * 
     *  ScheduledExecutorService newScheduledThreadPool() 创建固定大小的线程池,可以延迟或定时的执行任务。
     *
     */
    public class TestThreadPool {
        public static void main(String[] args) {
            //1.创建线程池
            ExecutorService threadPool = Executors.newFixedThreadPool(5);
            ThreadPoolDemo demo = new ThreadPoolDemo();
            
            //2.为线程池中的线程分配任务
            for(int i = 0;i<10;i++){
                threadPool.submit(demo);
            }
            
            //3.关闭线程池
            threadPool.shutdown();  //等待现有线程池中的任务之心完毕,关闭线程池,在等待过程中不接收新的任务
            
            
        }
    }
    
    class ThreadPoolDemo implements Runnable{
        private int i = 0;
        @Override
        public void run() {
            while(i <= 100){
                System.out.println(Thread.currentThread().getName() + " : " + i++);
            }
        }
    }

     可以在线程池中放一个Callable任务,并且可以过去到返回结果

    package com.java.juc;
    
    import java.util.ArrayList;
    import java.util.List;
    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;
    
    /**
     * 一、线程池:提供了一个线程队列,队列中保存着所有等待状态的线程。避免了创建与销毁额外的开销,提高了响应的速度。
     * 
     * 二、线程池的体系结构:
     *     java.util.concurrent.Executor: 负责线程的使用与调度根接口。
     *         |--**ExecutorService 子接口:线程池的主要接口
     *             |--ThreadPoolExecutor 线程池的实现类
     *             |--ScheduledExecutorService 子接口:负责线程的调度
     *                 |--ScheduledThreadPoolExecutor : 继承 ThreadPoolExecutor 实现ScheduledExecutorService
     * 三、工具类:Executors
     *     ExecutorService newFixedThreadPool() :创建固定大小的线程池。
     *     ExecutorService newCachedThreadPool(): 创建无限大小的线程池,线程池中线程数量不固定,可根据需求自动更改。
     *     ExecutorService newSingleThreadPool() : 创建单个线程池,线程池中只有一个线程。
     * 
     *  ScheduledExecutorService newScheduledThreadPool() 创建固定大小的线程池,可以延迟或定时的执行任务。
     *
     */
    public class TestThreadPool {
        public static void main(String[] args) throws InterruptedException, ExecutionException {
            //1.创建线程池
            ExecutorService threadPool = Executors.newFixedThreadPool(5);
            ThreadPoolDemo demo = new ThreadPoolDemo();
            
            List<Future> futureList = new ArrayList<>();
            
            for(int i = 0; i<10; i++){
                Future<Integer> future = threadPool.submit(new Callable<Integer>() {
                    public Integer call(){
                        int num = 0;
                        for(int i = 0;i<=100;i++){
                            num+=i;
                        }
                        return num;
                    }
                });
                futureList.add(future);
            }
            
            for(int i = 0;i<futureList.size();i++){
                System.out.println(futureList.get(i).get());
            }
            
    //        //2.为线程池中的线程分配任务
    //        for(int i = 0;i<10;i++){
    //            threadPool.submit(demo);
    //        }
            
            //3.关闭线程池
            threadPool.shutdown();  //等待现有线程池中的任务之心完毕,关闭线程池,在等待过程中不接收新的任务
        }
    }
    
    class ThreadPoolDemo implements Runnable{
        private int i = 0;
        @Override
        public void run() {
            while(i <= 100){
                System.out.println(Thread.currentThread().getName() + " : " + i++);
            }
        }
    }

    5050
    5050
    5050
    5050
    5050
    5050
    5050
    5050
    5050
    5050

    用线程池启动定时器

    Executors.newScheduledThreadPool(3).schedule(
                    new Runnable() {
                        @Override
                        public void run() {
                            System.out.println("bombing!");
                        }
                    }, 
                    10, 
                    TimeUnit.SECONDS);

    还可以在上述代码中添加固定频率

    //固定频率 10秒后触发,每隔两秒后执行一次
            Executors.newScheduledThreadPool(3).scheduleAtFixedRate(
                    new Runnable() {
                        @Override
                        public void run() {
                            System.out.println("bombing!");
                        }
                    }, 
                    10, 
                    2,
                    TimeUnit.SECONDS);
            //在使用scheduleAtFixedRate 时java api没有提供在某个时间点触发,但API中提示可以通过计算,得到触发的事件点
            // For example, to schedule at a certain future date,
            // you can use: schedule(task, date.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS). 
  • 相关阅读:
    SAP Fiori Elements Object Page页面渲染原理
    使用SAP CRM中间件从ERP下载plant到CRM
    SAP ABAP数据库表字段checktable的实现原理
    使用SAP CRM中间件从ERP下载Customer的错误消息:Distribution channel is not allowed for sales organization
    使用SAP CRM中间件从ERP下载Customer的错误消息:Customer classification does not exist
    SAP CRM中间件Request download的警告信息:message Object is in status Wait
    SAP CRM中间件Request download的警告信息:Form of address 0001 not designated for organization
    使用SAP CRM中间件下载customer的错误消息:Number not in interval XXX – XXX
    使用SAP CRM中间件从ERP下载plant到CRM
    Flink实例(十六):FLINK 异步IO (一)简介
  • 原文地址:https://www.cnblogs.com/wq3435/p/6037069.html
Copyright © 2011-2022 走看看