线程池Java

xiaoxiao2023-03-22  47

为啥有的线程池?

在我们执行任务时,如果为每个任务创建一个新线程来执行的话,想想线程状态:新建、就绪、运行、销毁。这些都是需要消耗计算资源的;那么就用一个线程池,放置一部分线程,让他时刻处于运行状态,运行任务结束后,将线程归还线程池。这样,是不是就可以避免了新建和销毁的这两步?让一部分线程时刻处于就绪和运行状态,从而提高了线程执行效率。

线程池怎么创建?

Java通过Executors提供四种线程池,分别为:

newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。 newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。 newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。 newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行

线程池优点?也是为啥有的线程池?

重用存在的线程,减少对象创建、消亡的开销,性能佳。 可有效控制最大并发线程数,提高系统资源的使用率,同时避免过多资源竞争,避免堵塞。 提供定时执行、定期执行、单线程、并发数控制等功能

线程池监控线程任务?

任务ABC都使用线程池里的线程执行任务;线程池可以监控到任务完成状况。

package mytest; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; public class TestThreadPool { public static void main(String args[]) { ExecutorService executor = Executors.newFixedThreadPool(10); for(int i=0;i<5;i++) {//测试超过线程总数后;3*5=15个线程 executor.execute(new TaskA()); executor.execute(new TaskB()); executor.execute(new TaskC()); } ThreadPoolExecutor pool = ((ThreadPoolExecutor) executor); while(true) { System.out.println("线程总数:"+pool.getMaximumPoolSize()); System.out.println("活动总数:"+pool.getActiveCount()); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } } static class TaskA implements Runnable{ @Override public void run() { System.out.println("A任务"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } static class TaskB implements Runnable{ @Override public void run() { System.out.println("B任务"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } static class TaskC implements Runnable{ @Override public void run() { System.out.println("C任务"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } }

 

转载请注明原文地址: https://www.6miu.com/read-4987476.html

最新回复(0)