2017-04-25 25 views
0
Thread faculty = new Thread(() -> { 
       try { 
        while (true) { 


     boolean is_grab = false; 
        semp.acquire(); 
        if (candy > 0) { 
         System.out.println("No." + NO + " faculty grabs a candy"); 
         candy--; 
         is_grab = true; 
         System.out.println("Candy num left:" + candy); 
        } 
        semp.release(); 
        if (is_grab) { 
         Thread.sleep(1000); 
        } 
       } 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     }); 
     faculty.start(); 
    } 

在上面的代碼中,我使用信號量實現用於同步和 如果(is_grab){了Thread.sleep(1000); }可以被執行。代碼後同步塊是不可訪問但semp.release()不是

然而,在下面的代碼,

Thread faculty = new Thread(() -> { 
       synchronized (Bowl.class) { 
        while (true) { 
         while (Bowl.candy <= 0) { 
          try { 
           Bowl.class.wait(); 
          } catch (InterruptedException e) { 
           e.printStackTrace(); 
          } 
         } 
         System.out.println("No." + NO + " faculty grabs a candy"); 
         Bowl.candy--; 
         System.out.println("Candy num left:" + Bowl.candy); 
         Bowl.class.notifyAll(); 
        } 
       } 
       try { 
        Thread.sleep(1000); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
      }); 

我使用同步上Bowl.class但嘗試{}睡眠不可達。爲什麼?

+1

沒有代碼突破循環。 – shmosel

+0

第一個片段中的'sleep'是'while(true)'的一部分。但是第二個片段中的'sleep'在'while(true)'後面,但是在同一個線程中。由於'while(true)'無法逃脫,執行永遠無法進入'sleep'。 –

+0

謝謝。我太sl。了。 –

回答

0

在下面的示例中,沒有break語句退出while(true)循環。

相關問題