gpt4 book ai didi

java - JAVA 线程池示例

转载 作者:行者123 更新时间:2023-12-01 08:14:41 25 4
gpt4 key购买 nike

任何人都可以给我一个简单的例子,在这个例子中我们创建了自己的线程池类以更好地了解线程。我不想使用java中可用的Executor Service。我的意思是线程池的任何内置类。

谢谢

最佳答案

这似乎就是您要找的。 http://java.dzone.com/news/java-concurrency-thread-pools

public class ThreadPool {

private BlockingQueue taskQueue = null;
private List<PoolThread> threads = new ArrayList<PoolThread>();
private boolean isStopped = false;

public ThreadPool(int noOfThreads, int maxNoOfTasks){
taskQueue = new BlockingQueue(maxNoOfTasks);

for(int i=0; i<noOfThreads; i++){
threads.add(new PoolThread(taskQueue));
}
for(PoolThread thread : threads){
thread.start();
}
}

public void synchronized execute(Runnable task){
if(this.isStopped) throw
new IllegalStateException("ThreadPool is stopped");

this.taskQueue.enqueue(task);
}

public synchronized void stop(){
this.isStopped = true;
for(PoolThread thread : threads){
thread.stop();
}
}

}



public class PoolThread extends Thread {

private BlockingQueue taskQueue = null;
private boolean isStopped = false;

public PoolThread(BlockingQueue queue){
taskQueue = queue;
}

public void run(){
while(!isStopped()){
try{
Runnable runnable = (Runnable) taskQueue.dequeue();
runnable.run();
} catch(Exception e){
//log or otherwise report exception,
//but keep pool thread alive.
}
}
}

public synchronized void stop(){
isStopped = true;
this.interrupt(); //break pool thread out of dequeue() call.
}

public synchronized void isStopped(){
return isStopped;
}
}

关于java - JAVA 线程池示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14450796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com