java实现多线程的各种方式(包括线程池)

   声明:本站部分内容来自互联网,如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

30

这是所有的常用方式,先列举一下,详情有博文逐一介绍。

1、线程池

1.1、固定大小的线程池,可以用于已知并发压力的情况下,对线程数做限制。(最基本的线程池)

ExecutorService executorService1 = Executors.newFixedThreadPool(3);

https://blog.csdn.net/qq_40308101/article/details/105122366

 

1.2、线程池不对线程池大小做限制,线程池大小完全依赖于操作系统能够创建的最大线程大小。(如果线程空闲时间超过了60秒就会被回收)

ExecutorService executorService2 = Executors.newCachedThreadPool();

https://blog.csdn.net/qq_40308101/article/details/105124394

 

1.3、单线程的线程池,可以用于需要保证顺序执行的场景,并且只有一个线程在执行。(另起一个单线程作为子线程)

ExecutorService executorService3 = Executors.newSingleThreadExecutor();

https://blog.csdn.net/qq_40308101/article/details/105125537

 

1.4、可以延时启动、定时启动的线程池,适用于需要多个后台线程执行周期任务的场景。(功能最多)

ScheduledExecutorService executorService4 = Executors.newScheduledThreadPool(3);

https://blog.csdn.net/qq_40308101/article/details/105118177

 

1.5、有多个任务队列的线程池,可以减少连接数,创建当前可用cpu数量的线程来并行执行。(jdk1.8版本推出的)

ExecutorService executorService5 = Executors.newWorkStealingPool();

https://blog.csdn.net/qq_40308101/article/details/105125707

 

2、通过实现 Runnable 接口;

https://blog.csdn.net/qq_40308101/article/details/105146167

 

3、通过继承 Thread 类本身;

https://blog.csdn.net/qq_40308101/article/details/105195755

 

4、通过 Callable 和 Future 创建线程。

https://blog.csdn.net/qq_40308101/article/details/105202227