ThreadPoolExecutor basic example 본문

Programming/Java

ThreadPoolExecutor basic example

halatha 2011. 4. 8. 05:12
//	http://programmingexamples.wikidot.com/threadpoolexecutor
import java.util.concurrent.*;
import java.util.*;

class TestThreadPoolExecutor {
	int	poolSize = 2;
	int	maxPoolSize = 2;
	long	keepAliveTime = 10;

	ThreadPoolExecutor	threadPool = null;

	final ArrayBlockingQueue queue =
		new ArrayBlockingQueue(5);

	public TestThreadPoolExecutor() {
		threadPool = new ThreadPoolExecutor(poolSize, maxPoolSize,
				keepAliveTime, TimeUnit.SECONDS, queue);
	}

	public void runTask(Runnable task) {
		// System.out.println("Task count.."+threadPool.getTaskCount() );
		// System.out.println("Queue Size before assigning the
		// task.."+queue.size() );
		threadPool.execute(task);
		// System.out.println("Queue Size after assigning the
		// task.."+queue.size() );
		// System.out.println("Pool Size after assigning the
		// task.."+threadPool.getActiveCount() );
		// System.out.println("Task count.."+threadPool.getTaskCount() );
		System.out.println("Task count.." + queue.size());
	}

	public void shutDown() {
		threadPool.shutdown();
	}

	public static void main(String args[]) {
		TestThreadPoolExecutor mtpe = new TestThreadPoolExecutor();
		mtpe.runTask(new TestThread("First Task", 1000));
		mtpe.runTask(new TestThread("Second Task", 1000));
		mtpe.runTask(new TestThread("Third Task", 1000));
		mtpe.runTask(new TestThread("Fourth Task", 1000));
		mtpe.runTask(new TestThread("Fifth Task", 1000));
		mtpe.runTask(new TestThread("Sixth Task", 1000));
		mtpe.shutDown();
	}
}

class TestThread implements Runnable {
	private String msg;
	private int	time;
	public TestThread(String msg, int time) {
		this.msg	=	msg;
		this.time	=	time;
	}
	public void run() {
		for (int i = 0; i < 10; i++) {
			try {
				System.out.println(msg);
				Thread.sleep(time);
			} catch (InterruptedException ie) { }
		}
	}
}

Comments