java--ThreadPool线程池简单用法

来源:互联网 发布:java poi 自动列宽 编辑:程序博客网 时间:2024/06/05 16:57
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
原创粉丝点击