12.线程池

线程池原理:

    一个线程池中有多个处于可运行状态的线程,当向线程池中添加Runnable或Callable接口对象时,    就会有一个线程来执行run()方法或call()方法。如果方法执行完毕,则该线程并不终止,

    而是继续在池中处于可运行状态,以运行新的任务。

为什么要用线程池:    

public class ThreadCondition implements Runnable {


private static int count=0;

@Test
public void testThreadPool(){
   Runtime run=Runtime.getRuntime();//当前程序运行对象
    run.gc();//调用垃圾回收机制,减少内存误差
    Long freememroy=run.freeMemory();//获取当前空闲内存
    Long protime=System.currentTimeMillis();
    for(int i=0;i<10000;i++){
      new Thread(new ThreadCondition()).start();
    }
    System.out.println("独立创建"+10000+"个线程需要的内存空间"+(freememroy-run.freeMemory()));
    System.out.println("独立创建"+10000+"个线程需要的系统时间"+(System.currentTimeMillis()-protime));


    System.out.println("---------------------------------");
    Runtime run2=Runtime.getRuntime();//当前程序运行对象
    run2.gc();//调用垃圾回收机制,减少内存误差
    Long freememroy2=run.freeMemory();//获取当前空闲内存
    Long protime2=System.currentTimeMillis();
   ExecutorService service=Executors.newFixedThreadPool(2);
    for(int i=0;i<10000;i++){
     service.execute(new ThreadCondition()) ;
    } 
    System.out.println("线程池创建"+10000+"个线程需要的内存空间"+(freememroy2-run.freeMemory()));
    service.shutdown();
   
    System.out.println("线程池创建"+10000+"个线程需要的系统时间"+(System.currentTimeMillis()-protime2));
 

}

@Override
public void run() {
//System.out.println(count++);
}

独立创建10000个线程需要的内存空间3897440

独立创建10000个线程需要的系统时间1049

---------------------------------

线程池创建10000个线程需要的内存空间373088

线程池创建10000个线程需要的系统时间29

   我们知道使用线程池可以大大的提高系统的性能,提高程序任务的执行效率,    节约了系统的内存空间。在线程池中,每一个工作线程都可以被重复利用,可执行多个任务,

    减少了创建和销毁线程的次数。能够根据系统的承受能力,调整其线程数目,以便使系统达到运行的最佳效果。

猜你喜欢

转载自blog.csdn.net/zzh8578741/article/details/81409375