如何在线程池中编写run方法

时间:2013-01-22 13:16:24

标签: java multithreading threadpool

通过阅读Thread Pooling我感到非常困惑。我学会了这个概念,它们是如何运作的。 但我在这部分中感到困惑,如何对此进行编码。

我在网上搜索了很多。最后我得到了一个博客,其代码如下,

条件是,不使用内置类

代码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??

帮助我。

提前致谢。

2 个答案:

答案 0 :(得分:2)

  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.

如果任务抛出异常,则不执行任何操作,只是不要传递它。

      }
    }
  }

答案 1 :(得分:1)

修改

我现在明白这是一个班级项目,但我会留下我的答案给后人。

如果您尝试在Java下使用线程池,那么java.util.concurrent.*类已经为您实现了所有这些。其他答案解决并解释您的具体代码。

例如,这是使用ExecutorService代码设置线程池所需的内容。在封面下方,ExecutorService处理线程并使用LinkedBlockingQueue。您定义实现'Runnable'的MyJob类,并执行池中线程运行的工作。根据您的需要,它可以是短期或长期运行的任务。

// create a thread pool with 10 workers
ExecutorService threadPool = Executors.newFixedThreadPool(10);
// or you can create an open-ended thread pool
// ExecutorService threadPool = Executors.newCachedThreadPool();
// define your jobs somehow
for (MyJob job : jobsToDo) {
    threadPool.submit(job);
}
// once we have submitted all jobs to the thread pool, it should be shutdown
threadPool.shutdown();
...
public class MyJob implements Runnable {
    // you can construct your jobs and pass in context for them if necessary
    public MyJob(String someContext) {
        ...
    }
    public void run() {
        // process the job
    }
}