通过阅读线程池,我非常困惑。我学到了这个概念,他们是如何实际工作的。 但是我在这个部分感到困惑,怎么编码呢。如何在线程池中运行代码的方法
我在网上搜了很多。最后,我得到了一个博客,有代码,如下,
条件是不使用内置类
代码1
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();
}
}
}
代码2
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;
}
}
代码3: -
public class BlockingQueue {
private List queue = new LinkedList();
private int limit = 10;
public BlockingQueue(int limit){
this.limit = limit;
}
public synchronized void enqueue(Object item)
throws InterruptedException {
while(this.queue.size() == this.limit) {
wait();
}
if(this.queue.size() == 0) {
notifyAll();
}
this.queue.add(item);
}
public synchronized Object dequeue()
throws InterruptedException{
while(this.queue.size() == 0){
wait();
}
if(this.queue.size() == this.limit){
notifyAll();
}
return this.queue.remove(0);
}
}
我试着理解,这段代码做了什么。 但我没有得到这个代码的流程。你能帮我理解这段代码吗?
Mainly I have problems in **Code 2 :- run method**
Why execute method's argument are of Runnable type?
How input array given to this code??
帮帮我。
在此先感谢。
为什么你必须编写自己的线程池?最容易使用执行者。* ThreadPool()方法创建一个线程池,然后使用提交(*)方法来提交Callable或Runnable。 – allprog
@allprog:我创建了该代码,该代码很容易构建。但是,我的老师要求在不使用内置课程的情况下进行构建。这就是为什么我发布这个。 – devsda
不错,你让社区检查作业。 :)不幸的是,执行ExecutorService的权利很难。如果您提供取消异步Future接口,那么您必须非常小心。您应该查看JDK源代码以获得正确的实现。这将比现在复杂得多。 – allprog