執行緒間的通信
執行緒通信就是執行緒與執行緒間進行資訊的交換,
這里可以舉個例子,兩個執行緒交替的列印0-9這10個數字,
首先分析一下,比如執行緒一先開始列印,當它列印了數字0后,他應該等待執行緒二列印數字1,執行緒二列印了之后又要等待執行緒一列印數字2...
那怎么樣才能讓執行緒一開始等待呢?這里可以使用Object類中的wait()方法,
代碼演示:
public class ThreadTest5 {
public static void main(String[] args) {
Number number = new Number();
Thread t1 = new Thread(number,"小明");
Thread t2 = new Thread(number,"小紅");
t1.start();
t2.start();
}
}
class Number implements Runnable{
private int num = 1;
@Override
public void run() {
while (true){
synchronized(this) {
//notify();//喚醒執行緒,讓執行緒進入就緒狀態等待CPU調度
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (num < 10) {
System.out.println(Thread.currentThread().getName() + num++);
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
break;
}
}
}
}
}
如果只有wait()方法,那么兩個執行緒都會進入阻塞狀態,

所以需要使用notify()或notifyAll()來喚醒執行緒,讓他們進入就緒狀態,
如果有多個執行緒進行列印,那么需要使用notifyAll()方法,
notif()方法會喚醒一個阻塞狀態的執行緒,如果有多個執行緒是阻塞狀態,會喚醒優先級高的執行緒,
notifyAll()方法會將所有的阻塞狀態的執行緒喚醒,
wait()方法會讓執行緒進入阻塞狀態并釋放當前的鎖物件,
注意:wait()、notify()和、notifyAll()方法必須在同步方法或者同步代碼塊中使用,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/194138.html
標籤:Java
上一篇:推薦 5 款牛逼的代碼編輯器
