Java代码
package demo;
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 = 1; 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();
}
}
}
} 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;
}
}
Java代码
package demo;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;public class ThreadPoolExecutorTest
{ private static int queueDeep = 4;
public void createThreadPool()
{
ThreadPoolExecutor tpe = new ThreadPoolExecutor(2, 4, 3, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(queueDeep),
new ThreadPoolExecutor.DiscardOldestPolicy()); // 向线程池中添加 10 个任务
for (int i = 0; i < 10; i++)
{
try
{
Thread.sleep(1);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
while (getQueueSize(tpe.getQueue()) >= queueDeep)
{
System.out.println("队列已满,等3秒再添加任务");
try
{
Thread.sleep(3000);
}
catch (InterruptedException e)
ThreadPoolExecutor 禁止shutdown threadpool execute
转载本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
Java 线程池 ThreadPoolExecutor
记录线程池的使用
线程池 java ide -
ThreadPoolExecutor shutdown线程资源未释放 threadpoolexecutor关闭
文章目录1.类结构2. 线程池流程和execute方法2.1 addWorKer()方法2.2 Work 的runWorker方法3. 线程池空闲线程的释放4. 线程池的关闭4.1 shutdown和shutdownNow4.2 共同方法:tryTerminate 1.类结构Executor接口。该接口定义执行器执行方法execute。ExecutorService接口。该接口定义管理执行器的一
线程池 execute shutdown ThreadPoolExecutor java