进阶day06-线程池的创建--方式二Executors
This commit is contained in:
34
javaSE-day06/src/com/inmind/thread_pool10/Demo12.java
Normal file
34
javaSE-day06/src/com/inmind/thread_pool10/Demo12.java
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
package com.inmind.thread_pool10;
|
||||||
|
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
|
||||||
|
/*
|
||||||
|
线程池的创建--方式二Executors
|
||||||
|
Executors的静态方法:
|
||||||
|
1.static ExecutorService newFixedThreadPool(int nThreads) 创建一个固定线程的线程池
|
||||||
|
2.static ExecutorService newSingleThreadExecutor() 创建一个只有一个线程的线程池,如果该线程出现异常,那么线程池主动创建一个新的替代
|
||||||
|
3.static ExecutorService newCachedThreadPool() 创建出随任务增加而增加线程的线程池,如果一个线程执行任务之后空闲了60s,这个线程就会被回收
|
||||||
|
|
||||||
|
注意:在实际开发中,不推荐使用Executors来创建线程池,工具类创建线程的底层其实就是ThreadPoolExecutor构造方法,只不过参数不同。
|
||||||
|
咱们的线程池的参数,要根据不同的业务来动态调整(而不是写死)
|
||||||
|
*/
|
||||||
|
public class Demo12 {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
ExecutorService threadPool = Executors.newFixedThreadPool(3);
|
||||||
|
MyRunnable task = new MyRunnable();
|
||||||
|
//将任务交给线程池的核心线程处理
|
||||||
|
threadPool.execute(task);
|
||||||
|
threadPool.execute(task);
|
||||||
|
threadPool.execute(task);
|
||||||
|
//3个核心线程被占用,4个任务队列
|
||||||
|
threadPool.execute(task);
|
||||||
|
threadPool.execute(task);
|
||||||
|
threadPool.execute(task);
|
||||||
|
threadPool.execute(task);
|
||||||
|
//核心线程和任务队列都占满,创建临时线程
|
||||||
|
threadPool.execute(task);
|
||||||
|
threadPool.execute(task);
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user