线程池

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
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 newSingleThreadExecutor() 创建单个线程池,线程池中只有一个线程
 * 
 *         ScheduledExecutorService newScheduledThreadPool() 创建固定大小的线程,可以延时或定时地执行任务
 */
public class ThreadPoolDemo {
    public static void main(String[] args) throws Exception {
        // 创建线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(5);

        List<Future<Integer>> list = new ArrayList<>();
        for (int j = 0; j < 10; j++) { // 十个任务
            Future<Integer> future = threadPool.submit(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    int sum = 0;
                    for (int i = 0; i <= 100; i++) {
                        sum += i;
                    }
                    return sum;
                }
            });
            list.add(future);
        }

        threadPool.shutdown(); // 关闭资源

        for (Future<Integer> future : list) {
            System.out.println(future.get());
        }

    }
}

3.1 线程调度

import java.util.Random;
import java.util.concurrent.*;

public class ScheduledThreadPoolDemo {
    public static void main(String[] args) throws Exception{
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);

        for (int i = 0; i < 5; i++) {
            ScheduledFuture<Integer> scheduledFuture = scheduledExecutorService.schedule(new Callable<Integer>() {
                int num = new Random().nextInt(100);
                @Override
                public Integer call() throws Exception {
                    System.out.println(Thread.currentThread().getName()+"---"+num);
                    return num;
                }
            },2, TimeUnit.SECONDS);

            System.out.println(scheduledFuture.get());
        }

        scheduledExecutorService.shutdown();
    }
}