java 多线程的一种实现方式

  private ThreadPoolExecutor threadPoolExecutor;



  /**
     * 获取线程池
     * @return
     */
    private ThreadPoolExecutor getThreadPoolExecutor(){
        if(threadPoolExecutor != null){
            return threadPoolExecutor;
        }
        threadPoolExecutor = new ThreadPoolExecutor(5,20,10, TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(2));
        return threadPoolExecutor;
    }



    public static void main(String str){

        getThreadPoolExecutor().execute(()->{
            //要执行的方法,调用
           runMethod();
        });
}
public void runMethod(){ int a = 10; }

注意点:

1.线程的生命周期开销非常高

2.消耗过多的CPU资源

如果可运行的线程数量多于可用处理器的数量,那么有线程将会被闲置。大量空闲的线程会占用许多内存,给垃圾回收器带来压力,而且大量的线程在竞争CPU资源时还将产生其他性能的开销。

降低稳定性

3.JVM在可创建线程的数量上存在一个限制,这个限制值将随着平台的不同而不同,并且承受着多个因素制约,包括JVM的启动参数、Thread构造函数中请求栈的大小,以及底层操作系统对线程的限制等。如果破坏了这些限制,那么可能抛出OutOfMemoryError异常。

4.线程过多时会报内存不足的情况,特别是访问量很大时谨慎使用多线程,报错的代码忘了 (如果任务过多处理不过来可以使用队列来执行对应任务,减轻CPU压力)

猜你喜欢

转载自www.cnblogs.com/procedureMonkey/p/9935005.html