线程池ThreadPoolExecutor和ExecutorService

线程池ExecutorService和ThreadPoolExecutor
ExecutorService返回的线程池对象的弊端如下:1)FixedThreadPool和SingleThreadPool:允许的请求队列长度为Integer.MAX_VALUE,可能会堆积大量的请求,从而导致OOM。2)CachedThreadPool和ScheduledThreadPool:允许的创建线程数量为Integer.MAX_VALUE,可能会创建大量的线程,从而导致OOM

  1.线程方法类
    public class MyThread extends Thread{
    	@Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "(自定义)正在执行。。。");
            for (int i = 0; i < 10; i++) {
            	//Timer timer = new Timer();
            	System.out.println(Thread.currentThread().getName()+"=="+i);
    		}
        }	
    }
    
    2.线程池ExecutorService和ThreadPoolExecutor测试类
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.LinkedBlockingQueue;
    import java.util.concurrent.ScheduledThreadPoolExecutor;
    import java.util.concurrent.ThreadPoolExecutor;
    import java.util.concurrent.TimeUnit;
    
    /**
     * 
     * @author zouyang
     * (推荐使用)
     * 创建一个可缓存的线程池。如果线程池的大小超过了处理任务所需要的线程,
     * 那么就会回收部分空闲(60秒不执行任务)的线程
     *
     */
    
    public class TestCachedThreadPool {
    
    	public static void main(String[] args) {
    	
    		//ExecutorService测试方法
    		//创建一个可重用固定线程数的线程池
            ExecutorService pool = Executors.newCachedThreadPool();
            
			//创建一个可重用固定线程数的线程池
        	//ExecutorService pool = Executors.newFixedThreadPool(1);//指定个数

            //创建实现了Runnable接口对象,Thread对象当然也实现了Runnable接口
           /* Thread t1 = new MyThread();
            Thread t2 = new MyThread();
            Thread t3 = new MyThread();
            Thread t4 = new MyThread();
            Thread t5 = new MyThread();        
            //将线程放入池中进行执行
            pool.execute(t1);
            pool.execute(t2);
            pool.execute(t3);
            pool.execute(t4);
            pool.execute(t5);
            */
            for (int i = 0; i < 5; i++) {
            	//Thread t1 = new MyThread();
            	//pool.execute(t1);
    		}
            pool.shutdown();//关闭线程池
    
    		//ThreadPoolExecutor测试方法
            System.out.println("ThreadPoolExecutor线程池");
            ThreadPoolExecutor tpe = new ThreadPoolExecutor(5, 10, 10, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(10));
            for (int i = 0; i < 5; i++) {
            	Thread t1 = new MyThread();
            	tpe.execute(t1);
    		}
            tpe.shutdown();//关闭线程池
            
    	}
    
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章