一、wait方法的概述
public final void wait() throws InterruptedException
wait方法是Object類中的一個方法,用於讓當前線程進入等待狀態,直到其他線程調用該對象的notify或notifyAll方法才可以喚醒它。調用wait方法必須使用在synchronized中,由於這個原因,wait方法只能夠被在同步塊內或者同步方法中調用,否則會拋出IllegalMonitorStateException。在調用wait方法時,線程會釋放掉它所持有的鎖,這樣其他線程就可以進入到同步塊或者同步方法中執行相應的代碼。
二、wait方法的用法
wait方法常用於實現線程的互斥機制,通過wait和notify的配合使用,不同的線程可以協調運行。
wait方法的一般用法是:
- 獲取要運行的線程對象
- 在同步塊中調用線程對象的wait方法
- 在另一個線程中調用線程對象的notify或者notifyAll方法,通知要運行的線程喚醒
下面是一個使用wait和notify實現生產者消費者模型的示例代碼:
public class ProducerConsumerExample { public static void main(String[] args) { Product product = new Product(); new ProducerThread(product).start(); new ConsumerThread(product).start(); } static class ProducerThread extends Thread { private Product product; ProducerThread(Product product) { this.product = product; } @Override public void run() { while (true) { synchronized (product) { while (product.getCount() >= Product.MAX_COUNT) { try { product.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } product.incrementCount(); System.out.println("生產了1個產品,當前產品數量為:" + product.getCount()); product.notifyAll(); } } } } static class ConsumerThread extends Thread { private Product product; ConsumerThread(Product product) { this.product = product; } @Override public void run() { while (true) { synchronized (product) { while (product.getCount() <= 0) { try { product.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } product.decrementCount(); System.out.println("消費了1個產品,當前產品數量為:" + product.getCount()); product.notifyAll(); } } } } static class Product { private int count; static final int MAX_COUNT = 10; int getCount() { return count; } void incrementCount() { count++; } void decrementCount() { count--; } }}
三、wait方法的注意事項
1、wait方法會釋放鎖
在執行wait方法之前,線程必須先獲得鎖,wait方法會釋放該鎖,使得其他線程可以獲得這個鎖。當wait方法返回後,當前線程又會重新獲取這個鎖。
2、wait方法可能會出現虛假喚醒
虛假喚醒是指,當一個線程調用了wait方法進入了等待狀態,即使沒有其他線程調用notify或notifyAll方法也有可能會被喚醒。對於此問題,可以在while循環中使用wait方法,循環條件為需要等待的條件。
3、線程調用interrupt方法可以中斷wait方法
當一個線程在等待狀態中,另一個線程調用了它的interrupt方法時,這個線程會拋出InterruptedException異常,從而退出等待狀態。因此,在使用wait方法時要注意捕獲InterruptedException異常。
四、總結
wait方法是實現線程等待和通知的重要手段,可以通過配合notify或notifyAll實現線程的協作運行。但是在使用wait方法時,需要考慮到線程的安全性,防止出錯。
原創文章,作者:VCLO,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/149142.html