`
cloud21
  • 浏览: 396388 次
  • 性别: Icon_minigender_2
  • 来自: 北京
社区版块
存档分类
最新评论

线程池之ThreadPoolExecutor

阅读更多
package blockingqueue;

import java.io.Serializable;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TestThreadPool2 {

	private static int produceTaskSleepTime = 2;

	private static int produceTaskMaxNumber = 10;

	public static void main(String[] args) {
		ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 4, 3,
				TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3),
				new ThreadPoolExecutor.DiscardOldestPolicy());

		for (int i = 0; i < produceTaskMaxNumber; i++) {
			try {
				String task = "task@" + i;
				System.out.println("put" + task);
				threadPool.execute(new ThreadPoolTask(task));

				Thread.sleep(produceTaskSleepTime);

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public static class ThreadPoolTask implements Runnable, Serializable {
		private static final long serialVersionUID = 0;
		private static int consumeTaskSleepTime = 2000;
		// 保存任务所需要的数据
		private Object threadPoolTaskData;

		ThreadPoolTask(Object tasks) {
			this.threadPoolTaskData = tasks;
		}

		public void run() {
			// 处理一个任务,这里的处理方式太简单了,仅仅是一个打印语句
			System.out.println(Thread.currentThread().getName());
			System.out.println("start .." + threadPoolTaskData);

			try {
				// //便于观察,等待一段时间
				Thread.sleep(consumeTaskSleepTime);
			} catch (Exception e) {
				e.printStackTrace();
			}
			threadPoolTaskData = null;
		}

		public Object getTask() {
			return this.threadPoolTaskData;
		}
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics