java并发编程test之使用线程池的效率对比

随机对比,一个是线程池使用方法 一个是不用线程池使用方法

产生一个随机整数,并且把这个随机整数加入到一个队列中

 

package com.test.java;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ExecutorTest {
	public static void main(String[] args) throws InterruptedException {
		ThreadPoolTest t = new ThreadPoolTest();
		t.test(10000);
		t.t2(10000);
	}
}


class ThreadPoolTest{
	/**
	 * 使用线程池
	 * 耗费时间:17
	 * 数组大小:10000
	 * @param count
	 */
	public void test(int count){
		long startTime = System.currentTimeMillis();
		final List<Integer> l = new LinkedList<>();
		ThreadPoolExecutor tp = new ThreadPoolExecutor(1,1,60,TimeUnit.SECONDS,new LinkedBlockingDeque<Runnable>());
		final Random random = new Random();
		for(int i= 0;i<count;i++){
			tp.execute(new Runnable(){
				@Override
				public void run() {
					l.add(random.nextInt());
				}
			});
		}
		
		tp.shutdown();
		try {
			tp.awaitTermination(1, TimeUnit.DAYS);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("耗费时间:"+(System.currentTimeMillis()-startTime));
		System.out.println("数组大小:"+l.size());
	}
	/**
	 * 不用线程池
	 * 结果:
	 * 耗费时间:1979
	 * 数组大小:10000
	 * @param count
	 */
	public void t2(int count){
		long startTime = System.currentTimeMillis();
		final List<Integer> l = new LinkedList<>();
		final Random random = new Random();
		Thread thread;
		for (int i = 0; i < count; i++) {
			thread = new Thread(){
				public void run() {
					l.add(random.nextInt());
				}
			};
			thread.start();
			try {
				thread.join();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		System.out.println("耗费时间:"+(System.currentTimeMillis()-startTime));
		System.out.println("数组大小:"+l.size());
	}
	
}

 

其中,t1为使用线程池(ThreadPoolExecutor)方法, 一个是不使用,结果对比很明显:

 

ec9ae006f4fe64ef68928efe9c72047b655.jpg

上面两种方式的差异在于: 使用线程池的方式是复用线程,而不是使用线程池的方式是每次都要创建线程;

在JAVA中,我们主要使用的线程池就是ThreadPooExecutor,此外还有定时的线程池ScheduledPoolExecutor;

总结:

线程池可以减低创建线程的开销,线程池在执行结束后进行的是回收操作,而是不真正销毁线程;

 

转载于:https://my.oschina.net/java1314/blog/3000553

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值