简体   繁体   English

如何在线程池中编写运行方法的代码

[英]How to code run method in Thread pooling

I got very confused by reading Thread Pooling. 通过阅读线程池,我感到非常困惑。 I learnt the concept, how they actually works. 我了解了这个概念,以及它们实际上是如何工作的。 But I confused in the part , how to code this. 但是我对如何编码这一部分感到困惑。

I searched a lot on the net. 我在网上搜索了很多。 Finally I got a blog, that have codes , given below, 最后我得到了一个博客,上面有代码,

CONDITION IS, NOT TO USE IN-BUILT CLASS 条件是,不要使用内置类

Code 1 代码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();
    }
  }

}

Code 2 代码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;
  }
}

Code 3:- 代码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);
  }    
}

I tried to understand , what this code do. 我试图理解,这段代码是做什么的。 But I dont get the flow of this code. 但是我没有得到这段代码的流程。 Can you help me to understand this code. 您能帮我理解这段代码吗?

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

Help me. 帮我。

Thanks in advance. 提前致谢。

  public void run(){
    while(!isStopped()){

Loop until the thread pool is stopped. 循环直到线程池停止。

      try{
        Runnable runnable = (Runnable) taskQueue.dequeue();

Pull the head task off the task queue. 将头任务从任务队列中拉出。

        runnable.run();

Run the task. 运行任务。

      } catch(Exception e){
        //log or otherwise report exception,
        //but keep pool thread alive.

Do nothing special if the task throws an exception, just don't pass it on. 如果任务抛出异常,请不要做任何特殊的事情,只是不要将其传递出去。

      }
    }
  }

Edit: 编辑:

I now understand that this is a class project but I'll leave my answer for posterity. 我现在知道这是一个课堂项目,但我将保留后代的答案。

If you are trying to use thread-pools under Java then all of this has been already implemented for you by the java.util.concurrent.* classes. 如果您尝试在Java下使用线程池,那么java.util.concurrent.*类已经为您实现了所有这些功能。 Other answers address and explain your specific code. 其他答案可以解决并解释您的特定代码。

For example, this is what you need to setup a thread pool using the ExecutorService code. 例如,这就是使用ExecutorService代码设置线程池所需的内容。 Underneath the covers the ExecutorService handles the threads and uses a LinkedBlockingQueue . 在幕后, ExecutorService处理线程并使用LinkedBlockingQueue You define the MyJob class which implements 'Runnable' and does the work that is run by the threads in the pool. 您定义MyJob类,该类实现“ Runnable”并执行由池中的线程运行的工作。 It can be a short or a long running task depending on what you need. 根据您的需要,它可以是短期任务也可以是长期任务。

// 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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM