线程和线程池

来源:互联网 发布:营销数据分析的作用 编辑:程序博客网 时间:2024/05/01 11:44

 现在是多核的时代,面向多核编程很重要,因些基于java的并发和多线程编程很重要。 首先要提到的就是线程池,与每次需要创建线程相比,线程池可以降低创建线程的开销,这是因为线程池在线程执行结束后进行的是回收操作,而不是真正销毁线程。 

         我们用一个案例来说明:

        使用线程的方案:

       

int count=10000000;long startTime=System.currentTimeMillis();final List<Integer> l=new LinkedList<Integer>();final Random random=new Random();for( int i=0;i<count;i++){Thread thread=new Thread(){@Overridepublic void run() {l.add(   random.nextInt() );}};thread.start();}System.out.println(     System.currentTimeMillis() -startTime );System.out.println(    l.size() );

      使用线程池的方案:   

int count=10000000;long startTime=System.currentTimeMillis();final List<Integer> l=new LinkedList<Integer>();ThreadPoolExecutor tp=new ThreadPoolExecutor( 1,1,60,TimeUnit.SECONDS, (BlockingQueue<Runnable>) new LinkedBlockingQueue<Runnable>(count));final Random random=new Random();for( int i=0;i<count;i++){tp.execute(new Runnable(){@Overridepublic void run() {l.add(   random.nextInt() );}});}tp.shutdown();try {tp.awaitTermination(1, TimeUnit.DAYS );} catch (InterruptedException e) {e.printStackTrace();}System.out.println(     System.currentTimeMillis() -startTime );System.out.println(    l.size() );

从输出结果可以看出来,使用了线程池后,效率提升明显。 

0 0
原创粉丝点击