1. 簡介
當多個線程需要協同工作時,我們需要使用Java中的wait()方法來實現線程之間的同步。該方法會使線程暫停執行並釋放佔用的鎖,直到其他線程調用notify()或notifyAll()方法來通知它恢復執行。
2. wait()方法的使用
1. wait()方法的語法
public final native void wait(long timeout) throws InterruptedException;
public final void wait(long timeout, int nanos) throws InterruptedException;
public final void wait() throws InterruptedException;
wait()方法有三個重載形式:
- wait(long timeout):使當前線程等待指定的毫秒數,或直到被通知或中斷。
- wait(long timeout, int nanos):與wait(long timeout)相似,但增加了納秒級別的精度。
- wait():使當前線程一直等待,直到被通知或中斷。
2. wait()方法的原理
當線程調用wait()方法時,它會釋放掉佔有的鎖,並讓自己進入等待狀態,直到其他線程調用了notify()或notifyAll()方法來通知它。
調用wait()方法的線程必須擁有該對象的鎖。如果沒有,則會拋出IllegalMonitorStateException異常。
一旦線程被通知,它會重新嘗試獲取鎖,並繼續執行。
3. wait()方法的應用場景
wait()方法通常用於實現線程之間的同步。下面是一些常見的wait()方法的應用場景:
- 生產者和消費者模式:使用wait()和notify()方法來協調生產者和消費者線程的工作。當隊列為空時,消費者線程會調用wait()方法等待生產者放入數據;而當隊列已滿時,生產者線程會調用wait()方法等待消費者取走數據。
- 多線程協作:當多個線程需要互相協作時,可以使用wait()和notify()方法來實現線程之間的通信。
3. 示例代碼
1. 生產者與消費者
class Producer extends Thread {
Queue queue;
Producer(Queue queue) {
this.queue = queue;
}
public void run() {
while (true) {
synchronized (queue) {
while (queue.size() >= 10) {
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("生產者生產數據: " + queue.size());
queue.offer(1);
queue.notifyAll();
}
}
}
}
class Consumer extends Thread {
Queue queue;
Consumer(Queue queue) {
this.queue = queue;
}
public void run() {
while (true) {
synchronized (queue) {
while (queue.isEmpty()) {
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("消費者消費數據: " + queue.size());
queue.poll();
queue.notifyAll();
}
}
}
}
public class Main {
public static void main(String[] args) {
Queue queue = new LinkedList();
Thread producer = new Producer(queue);
Thread consumer = new Consumer(queue);
producer.start();
consumer.start();
}
}
2. 多線程協作
class Worker extends Thread {
private int id;
private Object prev;
private Object cur;
Worker(int id, Object prev, Object cur) {
this.id = id;
this.prev = prev;
this.cur = cur;
}
public void run() {
while (true) {
synchronized (prev) {
synchronized (cur) {
System.out.println("Worker " + id + " is working.");
cur.notifyAll();
}
try {
prev.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class Main {
private static final int n = 5;
public static void main(String[] args) {
Object[] objects = new Object[n];
for (int i = 0; i < n; i++) {
objects[i] = new Object();
}
Thread[] threads = new Thread[n];
for (int i = 0; i < n - 1; i++) {
threads[i] = new Worker(i, objects[i], objects[i + 1]);
}
threads[n - 1] = new Worker(n - 1, objects[n - 1], objects[0]);
for (Thread t : threads) {
t.start();
}
}
}
4. 總結
本文介紹了Java中的wait()方法,包括其語法、原理和應用場景。我們通過兩個示例代碼來演示了wait()方法的應用,一個是生產者和消費者模式,一個是多線程協作場景。wait()方法是實現線程之間同步通信的重要工具,我們在實際開發中需要充分理解其原理和應用場景,並適當運用它來提高應用程序的性能和穩定性。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/287145.html
微信掃一掃
支付寶掃一掃