天天看點

一個簡單線程池的實作

代碼比較簡單,有助于了解線程池,代碼如下:

public class ThreadPool {
    private int maxCount;
    private volatile boolean start = false;
    private BlockingQueue<Runnable> tasks;

    public ThreadPool() {
	this(10);
    }

    public ThreadPool(int threadMaxCount) {
	this.maxCount = threadMaxCount;
	tasks = new LinkedBlockingQueue<Runnable>();
    }

    public void task(Runnable task) {
	try {
	    tasks.put(task);
	} catch (InterruptedException e) {
	    e.printStackTrace();
	}
    }

    public void start() {
	if (start)
	    return;
	start = true;
	for (int i = 0; i < maxCount; i++)
	    new Thread(new Runnable() {
		@Override
		public void run() {
		    try {
			while (start)
			    tasks.take().run();
		    } catch (InterruptedException e) {
			e.printStackTrace();
		    }
		}
	    }).start();
    }

    public void stop() {
	this.start = false;
    }
}
           

測試代碼如下:

public class App {
    public static void main(String[] args) throws Exception {
	ThreadPool tp = new ThreadPool();
	tp.task(new Runnable() {

	    @Override
	    public void run() {
		System.out.println("Begin");
	    }
	});
	tp.start();
	for (int i = 0; i < 10; i++) {
	    Thread.sleep(1000);
	    tp.task(new Runnable() {

		@Override
		public void run() {
		    System.out.println(Thread.currentThread() + "doSomething!");
		}
	    });
	    tp.stop();
	}
    }

}