线程池下

本文介绍了一个简单的线程池实现方案,包括线程管理类、工作线程类及任务接口的设计。通过创建线程池并分配任务,演示了如何管理和调度线程执行指定任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

线程管理类:使用入口
public class ThreadPoolManager {

private static final int DEFAULT_POOL_SIZE = 4;
private List<WorkThread> threadPool;
private Queue<Task> taskQueue;
private int poolSize;

public ThreadPoolManager() {
this(DEFAULT_POOL_SIZE);
}

public ThreadPoolManager(int poolSize) {
if(poolSize <= 0) {
this.poolSize = DEFAULT_POOL_SIZE;
}else {
this.poolSize = poolSize;
}
threadPool = new ArrayList<WorkThread>(this.poolSize);
taskQueue = new ConcurrentLinkedQueue<Task>();
startup();
}

public void startup() {
System.out.println("start work thread...");
synchronized(taskQueue) {
for(int i = 0; i < this.poolSize; i++) {
WorkThread workThread = new WorkThread(taskQueue);
threadPool.add(workThread);
workThread.start();
}
}
}

public void shutdown() {
System.out.println("shutdown work thread...");
synchronized(taskQueue) {
for(int i = 0; i < this.poolSize; i++) {
threadPool.get(i).shutdown();
}

System.out.println("done...");
}
}

public void addTask(Task task) {
synchronized(taskQueue) {
taskQueue.add(task);
taskQueue.notify();
}
}
}
工作线程类:
public class WorkThread extends Thread {

private boolean shutdown = false;
private Queue<Task> queue;

public WorkThread(Queue<Task> queue) {
this.queue = queue;
}

public void run() {
while(!shutdown) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println(Thread.currentThread() + " is running...");
synchronized(queue) {
if(!queue.isEmpty()) {
Task task = queue.poll();
task.execute();
}else {
try {
queue.wait(1000);
System.out.println(Thread.currentThread() + " wait...");
}catch(InterruptedException e) {

}
}
}
}
}

public void shutdown() {
shutdown = true;
}
}

工作任务接口:
public interface Task {

public void execute();
}

工作任务类:
class SimpleTask implements Task {

/* (non-Javadoc)
* @see Task#execute()
*/
public void execute() {
System.out.println(Thread.currentThread());
}

}

线程池测试类:
public class ThreadPoolDemo {

public static void main(String[] args) {
ThreadPoolManager threadMg = new ThreadPoolManager();

for(int i = 0; i < 50; i++) {
threadMg.addTask(new SimpleTask());
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
threadMg.shutdown();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值