多线程编程-线程池

目录

1.线程池

2.标椎库中的线程池

3.线程池的实现


序列:多线程 - 011

1.线程池

线程池:申请一块内存专门用来保存线程。线程的创建与销毁都需要一定的损耗。

线程池的最大的好处就是减少每次启动和销毁线程的损耗。

2.标椎库中的线程池

  • 使用Executors.newFixedThreadPool(10)能创建出来固定包含10个线程的线程池;
  • 返回值的类型为ExecutorService;
  • 通过ExecutorService.submit可以注册一个任务到线程池中;

3.线程池的实现

/**
 * 模拟实现一个简单的线程池
 */
class MyThreadPool{
    //任务队列
    private BlockingQueue queue = new ArrayBlockingQueue(1000);

    //通过这个方法,把任务添加到队列中
    public void submit(Runnable runnable) throws InterruptedException {
        //此处拒绝策略,相当于第五种策略,阻塞等待
        queue.put(runnable);
    }
    public MyThreadPool(int n){
        //创建出 n 个线程,负责执行上述队列中的任务
        for (int i = 0; i < n; i++) {
            Thread thread = new Thread(()->{
                //让这个线程在队列中消费任务,并进行执行
                try {
                    Runnable runnable = queue.take();
                    runnable.run();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
            thread.start();
        }
    }
}

public class Demo01 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool myThreadPool = new MyThreadPool(4);
        for (int i = 0; i < 1000; i++) {
            int id = i;
            myThreadPool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("AAAAA...." + id);
                }
            });
        }
    }
}

你可能感兴趣的:(JavaEE,(初阶),jvm,java-ee)