每當對物件呼叫wait()方法時,它都會導致當前執行緒等待,直到另一個執行緒呼叫notify()或notifyAll( ) 該物件的方法,而wait(long timeout) 導致目前執行緒等待,直到另一個執行緒呼叫notify() 或 notifyAll( ) 該物件的方法,或已過了指定的逾時時間。
在下面的程式中,當 wait() 在物件上調用,執行緒從運行狀態進入等待狀態。它等待其他執行緒呼叫 notify() 或 notifyAll() 才能進入可運行狀態,將會形成死鎖。
class MyRunnable implements Runnable { public void run() { synchronized(this) { System.out.println("In run() method"); try { this.wait(); System.out.println("Thread in waiting state, waiting for some other threads on same object to call notify() or notifyAll()"); } catch (InterruptedException ie) { ie.printStackTrace(); } } } } public class WaitMethodWithoutParameterTest { public static void main(String[] args) { MyRunnable myRunnable = new MyRunnable(); Thread thread = new Thread(myRunnable, "Thread-1"); thread.start(); } }
In run() method
#在下面的程式中,當物件呼叫 wait(1000)時,執行緒從執行狀態進入等待狀態,即使在逾時時間過後沒有呼叫notify()或 notifyAll()執行緒也會從等待狀態進入可運作狀態。
class MyRunnable implements Runnable { public void run() { synchronized(this) { System.out.println("In run() method"); try { <strong> this.wait(1000); </strong> System.out.println("Thread in waiting state, waiting for some other threads on same object to call notify() or notifyAll()"); } catch (InterruptedException ie) { ie.printStackTrace(); } } } } public class WaitMethodWithParameterTest { public static void main(String[] args) { MyRunnable myRunnable = new MyRunnable(); Thread thread = new Thread(myRunnable, "Thread-1"); thread.start(); } }
In run() method Thread in waiting state, waiting for some other threads on same object to call notify() or notifyAll()
以上是在Java中,我們什麼時候可以呼叫Thread的wait()和wait(long)方法?的詳細內容。更多資訊請關注PHP中文網其他相關文章!