簡體   English   中英

如何在線程池中編寫運行方法的代碼

[英]How to code run method in 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??

幫我。

提前致謝。

  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.

如果任務拋出異常,請不要做任何特殊的事情,只是不要將其傳遞出去。

      }
    }
  }

編輯:

我現在知道這是一個課堂項目,但我將保留后代的答案。

如果您嘗試在Java下使用線程池,那么java.util.concurrent.*類已經為您實現了所有這些功能。 其他答案可以解決並解釋您的特定代碼。

例如,這就是使用ExecutorService代碼設置線程池所需的內容。 在幕后, ExecutorService處理線程並使用LinkedBlockingQueue 您定義MyJob類,該類實現“ Runnable”並執行由池中的線程運行的工作。 根據您的需要,它可以是短期任務也可以是長期任務。

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