1.在执行一个异步任务或并发任务时,往往是通过直接new Thread()
方法来创建新的线程,这样做弊端较多,更好的解决方案是合理地利用线程池,线程池的优势很明显,如下:
2.标准库中的线程池
package thread2;import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;public class Test5 {public static void main(String[] args) {ExecutorService pool = Executors.newFixedThreadPool(10);for (int i = 0; i < 100; i++) {pool.submit(new Runnable() {@Overridepublic void run() {System.out.println("hello");}});}}
}
Executors 创建线程池的几种方式
Executors 本质上是 ThreadPoolExecutor 类的封装.
ThreadPoolExecutor 提供了更多的可选参数, 可以进一步细化线程池行为的设定.
3.实现线程池
package thread2;import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;class MyThreadPool {private BlockingQueue queue = new LinkedBlockingQueue<>();static class Worker extends Thread {private BlockingQueue queue = null;public Worker(BlockingQueue queue) {this.queue = queue;}@Overridepublic void run() {while (true) {try {Runnable task = queue.take();task.run();} catch (InterruptedException e) {throw new RuntimeException(e);}}}}private List workerList = new ArrayList<>();public MyThreadPool(int n) {for (int i = 0; i < n; i++) {Worker worker = new Worker(queue);worker.start();workerList.add(worker);}}public void submit(Runnable runnable) {try {queue.put(runnable);} catch (InterruptedException e) {throw new RuntimeException(e);}}
}public class Test6 {public static void main(String[] args) {MyThreadPool myThreadPool = new MyThreadPool(10);for (int i = 0; i < 100; i++) {myThreadPool.submit(new Runnable() {@Overridepublic void run() {System.out.println("hello");}});}}
}