1. 程式人生 > >使用執行緒池和直接new 一個Thread執行對比

使用執行緒池和直接new 一個Thread執行對比

大家new Thread的方式會建立一個執行緒,在我們有大量的建立執行緒的時候這樣的方法還會可靠嗎?每一次new Thread都會重新建立一個執行緒,而執行緒的建立和銷燬都需要耗時的。在jdk1.5的concurrent包中有一個Executors,他能使我們建立的執行緒得到複用,不會頻繁的建立和銷燬執行緒。

在網上已經有很多博文介紹了Executors了,我們今天主要是我們使用了Executors和每次new一個Thread的對比。

測試程式碼:

package com.ys.concurrent.test001;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test001 {
	private ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<String>();
//	private ArrayList<String> queue = new ArrayList<String>();
//	private CyclicBarrier barrier = new CyclicBarrier(10000000);
	private CountDownLatch latch = new CountDownLatch(100000);
	ExecutorService es = Executors.newFixedThreadPool(4);
	public static void main(String[] args) {
		Test001 test001 = new Test001();
		long timeStart = System.currentTimeMillis();
		test001.start();
		System.out.println(System.currentTimeMillis()-timeStart);
	}
	
	public void start(){
		for (int i = 0; i < 100000; i++) {
			Runnable001 runnable001 = this.new Runnable001(i);
			es.submit(runnable001);
//			new Thread(runnable001).start();
		}
		es.shutdown();
		try {
			//等待latch計數為0
			latch.await();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(queue.size());
	}
	
	private class Runnable001 implements Runnable{
		private int value;
		public Runnable001(int value) {
			this.value = value;
		}
		@Override
		public void run() {
			try {
//				barrier.await();
			} catch (Exception e) {
				e.printStackTrace();
			}
			queue.offer(value+"");
			latch.countDown();//latch計數減一
		}
		
	}
}

首先是使用Executors的情況:執行結果如下:


註釋:es.submit(runnable001);放開:new Thread(runnable001).start();得到結果:


可見差距之大,(也不排除我使用的引數值不合理的情況);但是我們如果有大量的需要使用執行緒的話不妨考慮一下執行緒池。