JAVA中的线程池示例
谁能给我举个简单的例子,我们创建了自己的threadpool类来更好地理解线程。我不想使用java中可用的Executor服务。我指的是线程池的任何内置类JAVA中的线程池示例,java,threadpool,Java,Threadpool,谁能给我举个简单的例子,我们创建了自己的threadpool类来更好地理解线程。我不想使用java中可用的Executor服务。我指的是线程池的任何内置类 谢谢这似乎就是你要找的。 公共类线程池{ private BlockingQueue taskQueue=null; private List threads=new ArrayList(); 私有布尔值=false; 公共线程池(int-noOfThreads、int-maxNoOfTasks){ taskQueue=新的Blocking
谢谢这似乎就是你要找的。
公共类线程池{
private BlockingQueue taskQueue=null;
private List threads=new ArrayList();
私有布尔值=false;
公共线程池(int-noOfThreads、int-maxNoOfTasks){
taskQueue=新的BlockingQueue(maxNoOfTasks);
对于(inti=0;i这似乎就是您要寻找的。
公共类线程池{
private BlockingQueue taskQueue=null;
private List threads=new ArrayList();
私有布尔值=false;
公共线程池(int-noOfThreads、int-maxNoOfTasks){
taskQueue=新的BlockingQueue(maxNoOfTasks);
对于(int i=0;iExecutors是Java SE库的一部分。为什么不使用它们?它们提供了一个更有用的用于管理线程的API。我阅读了其中的部分内容。它有一个自建的示例,介绍了您必须处理的所有事情。执行者是Java SE库的一部分。为什么不使用它们呢?它们为我们提供了更多信息用于管理线程的完美API。我阅读了其中的部分内容。它有一个自建的示例,介绍了您需要处理的所有事情。谢谢大家…:)事实上,我想了解线程池的感觉。我想了解线程池的内部工作方式,例如如何选择(等待并通知)线程和分配任务。谢谢大家…:)实际上,我想了解线程池的感觉,我想知道线程池的内部工作原理,比如线程是如何挑选(等待和通知)和分配任务的。
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;
}
}