JAVA单排日记-2020/1/21-线程池

1.线程池思想概述

  • 频繁的消除和创建线程需要时间,对同一个线程反复的使用可以提高效率

2.线程池的概念

  • 线程池:线程的集合
LinkedList<Thread> threads = new LinkedList<>();

添加线程:

LinkedList<Thread> threads = new LinkedList<>();
threads.add(new Thread("线程1"));
threads.add(new Thread("线程2"));
threads.add(new Thread("线程3"));
threads.add(new Thread("线程4"));

调用线程:

Thread thread01 = threads.removeFirst();
Thread thread02 = threads.removeFirst();

使用完毕,还回线程

threads.addLast(thread01);
threads.addLast(thread02);

JDK1.5之后

  1. 使用线程池的工厂类Executors里面的静态方法newFixedThreadPool()生产一个指定数量的线程池
ExecutorService es = Executors.newFixedThreadPool(3); 生产3个线程,
  1. 创建一个Runnable接口的实现类,重写run()方法,设置线程任务
public class ImpRunnable implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}
  1. 使用ExecutorService中的方法submit(),传递线程任务(实现类),开启线程,执行run()方法
es.submit(new ImpRunnable());
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Demo05 {
    public static void main(String[] args) {
        ExecutorService es= Executors.newFixedThreadPool(3);
        es.submit(new ImpRunnable());
        es.submit(new ImpRunnable());
        es.submit(new ImpRunnable());
        es.submit(new ImpRunnable());

    }
}

在这里插入图片描述

  1. 使用ExecutorService中的方法shutdown()销毁线程池(不建议使用)
es.shutdown();
发布了90 篇原创文章 · 获赞 1 · 访问量 2030

猜你喜欢

转载自blog.csdn.net/wangzilong1995/article/details/104064046