package com.threadPool;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class TestThreadPool {
private static int produceTaskSleepTime = 0;
private static int produceTaskMaxNumber = 100000;
public static void main(String[] args) {
// 构造一个线程池
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(6, 100, 3,
TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3),
new ThreadPoolExecutor.DiscardOldestPolicy());
for (int i = 1; i <= produceTaskMaxNumber; i++) {
try {
String task = "task@ " + i;
System.out.println("创建任务并提交到线程池中:" + task);
threadPool.execute(new ThreadPoolTask(task));
Thread.sleep(produceTaskSleepTime);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
package com.threadPool;
import java.io.Serializable;
public class ThreadPoolTask implements Runnable, Serializable {
private Object attachData;
ThreadPoolTask(Object tasks) {
this.attachData = tasks;
}
public void run() {
System.out.println("开始执行任务:" + attachData);
attachData = null;
}
public Object getTask() {
return this.attachData;
}
}
输出结果:
开始执行任务:task@ 97856
开始执行任务:task@ 97857
创建任务并提交到线程池中:task@ 97858
创建任务并提交到线程池中:task@ 97859
开始执行任务:task@ 97858
开始执行任务:task@ 97859
创建任务并提交到线程池中:task@ 97860
.......
参考网站: http://my.eoe.cn/niunaixiaoshu/archive/4111.html