newFixedThreadPool
问题提出:
- jdk中关于newFixedThreadPool的叙述是:创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程。在任意点,在大多数 nThreads 线程会处于处理任务的活动状态。如果在所有线程处于活动状态时提交附加任务,则在有可用线程之前,附加任务将在队列中等待。如果在关闭前的执行期间由于失败而导致任何线程终止,那么一个新线程将代替它执行后续的任务(如果需要)。在某个线程被显式地关闭之前,池中的线程将一直存在。
- 什么叫可重用固定线程的线程池?
代码:
- 这个是我写的一个线程类,在打印完信息后睡眠个3秒钟
public class MyThread extends Thread{private boolean flag;public MyThread(boolean flag) {this.flag = flag;}@Overridepublic void run() {toString();try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("The thread has recall !");}@Overridepublic String toString(){System.out.println("NAME : " + this.getName() + " ID :" + this.getId());return null;}}
2. 第二个程序,启动一个newFixedThreadPool运行一下。
import java.util.ArrayList;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class TestPoolExecutor {public static void main(String[] args) {ExecutorService pool = Executors.newFixedThreadPool(3);ArrayList<MyThread>threads = new ArrayList<MyThread>();boolean flag = true;for(int i=0; i<10; i++){MyThread thread = new MyThread(flag);threads.add(thread);pool.execute(thread);}}}
3. 输出的情况
NAME : Thread-0 ID :9NAME : Thread-1 ID :11NAME : Thread-2 ID :13The thread has recall !NAME : Thread-3 ID :15The thread has recall !NAME : Thread-4 ID :16The thread has recall !NAME : Thread-5 ID :17The thread has recall !NAME : Thread-6 ID :18The thread has recall !NAME : Thread-7 ID :19The thread has recall !NAME : Thread-8 ID :20The thread has recall !NAME : Thread-9 ID :21The thread has recall !The thread has recall !The thread has recall !
结论:
- 可以看出,我启动了三个线程,在每个线程完成之后,又有一个新的线程进入线程池中,完成一些操作,之后在结束了该线程,重复添加线程,一直到所有的任务都完成为止!
newCachedThreadPool
newCachedThreadPoolpublic static ExecutorService newCachedThreadPool(ThreadFactory threadFactory)创建一个可根据需要创建新线程的线程池,但是在以前构造的线程可用时将重用它们,并在需要时使用提供的 ThreadFactory 创建新线程。参数:threadFactory - 创建新线程时使用的工厂返回:新创建的线程池抛出:NullPointerException - 如果 threadFactory 为 null
- 这个是CachedThreadPool的说明和解释,可以看到,该线程池的空间是由jvm来自己定义的,也就是说,你可以启动n个线程,但是运行与否得看,jvm的内存和每一个线程的情况。
- 额,电脑测试光荣事迹,死机码
import java.util.ArrayList;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class TestPoolExecutor {public static void main(String[] args) {ExecutorService pool = Executors.newCachedThreadPool();ArrayList<MyThread>threads = new ArrayList<MyThread>();for(int i=0; i<2000000; i++){MyThread thread = new MyThread(i);threads.add(thread);pool.execute(thread);}}}
3. 从这个可以得出一个深刻的结论:那就是让系统自行根据需求自行线程池不靠谱啊!