簡體   English   中英

喚醒等待線程

[英]wake up waiting threads

該課程與執行者一起工作。 事實是,在某個時候我想關閉它,但是即使我將terminateRequested更改為“ true”,它也不會幫助那些在“ takeTask”中等待的線程,因為此時的矢量任務始終為空。 我需要它們以某種方式到達run()中的“ e.shutDown()”行

public class RunnableStudent implements Runnable{

public void run() {

    while(!terminateRequested){

        this.takeTask();
        this.giveSolution();

    }


    e.shutdown();

}


private synchronized void takeTask(){


          while(tasks.isEmpty()){
               try {

                 this.wait();
              } catch (InterruptedException e) {

                 e.printStackTrace();
              }
          }

         DoSomeWork();
}

public synchronized void shutDown(){


    terminateRequested = true;
    this.notifyAll();

}

您將需要跳出while tasks.isEmpty()){循環,而跳出while(!terminateRequested){循環

所以我建議你做的時候

} catch (InterruptedException e) {
     e.printStackTrace();
}

您將其更改為

} catch (InterruptedException e) {
     terminateRequested = true;
     return;
}

由於看不到您的giveSolution方法,因此無法告訴您必須更改它。

另外,您可以通過takeTask方法中的InterruptedException

由於您使用的是執行程序服務,因此可以調用它的shutdownNow方法來主動關閉線程,而無需等待。

將Object.wait和Object.notify與java.util.concurrent氣味組合在一起, 是否直接使用Object.wait和Object.notify產生代碼氣味?

您需要打破while(tasks.isEmpty())的循環,因此需要更改代碼,如下所示:

public class RunnableStudent implements Runnable{

 private Thread thread;
 public void run() {

    thread = Thread.currentThread();
    while(!terminateRequested){

        this.takeTask();
        this.giveSolution();

   }


   e.shutdown();

 }

 private synchronized void takeTask(){


      while(tasks.isEmpty()){
           try {

             this.wait();
          } catch (InterruptedException e) {
             break;
          }
      }

     DoSomeWork();
}

public synchronized void shutDown(){

     terminateRequested = true;
     thread.interupt();

}

首先,如果您擁有三個不同的RunnableStudent實例(每個線程每個實例),並且假定任務和TerminateRequested是局部變量,則無需同步。因為線程之間沒有共享的對象。

其次,如果您使用執行程序,則可以使用線程池,這種情況下您無需等待並通知自己,一旦工作完成,則池中的所有線程(在池初始化時配置了n個線程)將等待下一個請求(通過executors.submit / execute)。 而且,您可以根據自己的情況在任何給定點使用shutdown / shutdownNow。

最后回答您的問題,只需將while循環更改為taketask()中的if條件。 您所有的問題都會解決。 因為您的等待邏輯在run方法中的main while循環中仍然會很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM