使用线程池与非线程池的区别
我们编写一段示例代码,来验证下线程池与非线程池的区别:
//线程池和非线程池的区别
public class ThreadPool {
public static int times = 100;//100,1000,10000
public static ArrayBlockingQueue arrayWorkQueue = new ArrayBlockingQueue(1000);
public static ExecutorService threadPool = new ThreadPoolExecutor(5, //corePoolSize线程池中核心线程数
10,
60,
TimeUnit.SECONDS,
arrayWorkQueue,
new ThreadPoolExecutor.DiscardOldestPolicy()
);
public static void useThreadPool() \{
Long start = System.currentTimeMillis();
for (int i = 0; i < times; i++) \{
threadPool.execute(new Runnable() \{
public void run() \{
System.out.println("说点什么吧...");
\}
\});
\}
threadPool.shutdown();
while (true) \{
if (threadPool.isTerminated()) \{
Long end = System.currentTimeMillis();
System.out.println(end - start);
break;
\}
\}
\}
public static void createNewThread() \{
Long start = System.currentTimeMillis();
for (int i = 0; i < times; i++) \{
new Thread() \{
public void run() \{
System.out.println("说点什么吧...");
\}
\}.start();
\}
Long end = System.currentTimeMillis();
System.out.println(end - start);
\}
public static void main(String args\[\]) \{
createNewThread();
//useThreadPool();
\}
}
启动不同数量的线程,然后比较线程池和非线程池的执行结果:
非线程池 | 线程池 | |
---|---|---|
100次 | 16毫秒 | 5ms的 |
1000次 | 90毫秒 | 28ms |
10000次 | 1329ms | 164ms |
结论:不要新的Thread(),采用线程池
非线程池的缺点:
- 每次创建性能消耗大
- 无序,缺乏管理。容易无限制创建线程,引起OOM和死机
还没有评论,来说两句吧...