Java多線程等待喚醒機(jī)制實(shí)例
在Java編程中,多線程的等待喚醒機(jī)制是一種重要的同步機(jī)制。通過(guò)使用wait()、notify()和notifyAll()方法,可以實(shí)現(xiàn)線程之間的協(xié)調(diào)與通信。下面將介紹一個(gè)簡(jiǎn)單的例子來(lái)演示Java中多
在Java編程中,多線程的等待喚醒機(jī)制是一種重要的同步機(jī)制。通過(guò)使用wait()、notify()和notifyAll()方法,可以實(shí)現(xiàn)線程之間的協(xié)調(diào)與通信。下面將介紹一個(gè)簡(jiǎn)單的例子來(lái)演示Java中多線程等待喚醒機(jī)制的應(yīng)用。
創(chuàng)建學(xué)生資源類
首先,我們創(chuàng)建一個(gè)`StudentDemo`類作為學(xué)生資源類,包含學(xué)生的姓名、年齡和一個(gè)標(biāo)識(shí)符`flag`。
```java
public class StudentDemo {
String name;
int age;
boolean flag;
}
```
創(chuàng)建設(shè)置線程類
接下來(lái),我們定義一個(gè)設(shè)置線程`SetThread`,實(shí)現(xiàn)了`Runnable`接口,用于設(shè)置學(xué)生的姓名和年齡。
```java
public class SetThread implements Runnable {
private StudentDemo s;
private int x 0;
public SetThread(StudentDemo s) {
this.s s;
}
@Override
public void run() {
while (true) {
synchronized (s) {
if (s.flag) {
try {
s.wait();
} catch (InterruptedException e) {
();
}
}
if (x % 2 0) {
"張三";
21;
} else {
"李四";
18;
}
x ;
s.flag true;
();
}
}
}
}
```
創(chuàng)建獲取線程類
然后,我們編寫(xiě)獲取線程`GetThread`,也實(shí)現(xiàn)了`Runnable`接口,用于獲取并打印學(xué)生的姓名和年齡。
```java
public class GetThread implements Runnable {
private StudentDemo s;
public GetThread(StudentDemo s) {
this.s s;
}
@Override
public void run() {
while (true) {
synchronized (s) {
if (!s.flag) {
try {
s.wait();
} catch (InterruptedException e) {
();
}
}
( " ---- " );
s.flag false;
();
}
}
}
}
```
注意事項(xiàng)
在使用`synchronized`關(guān)鍵字加鎖時(shí),設(shè)置線程和獲取線程必須使用同一把鎖,以確保線程同步的有效性。
運(yùn)行結(jié)果
在運(yùn)行程序后,我們可以看到輸出結(jié)果如下:
```
李四 ---- 18
張三 ---- 21
李四 ---- 18
張三 ---- 21
李四 ---- 18
張三 ---- 21
李四 ---- 18
張三 ---- 21
李四 ---- 18
張三 ---- 21
...
```
通過(guò)這個(gè)例子,我們可以清晰地了解Java中多線程的等待喚醒機(jī)制的實(shí)陵應(yīng)用方式及效果。