การสื่อสารระหว่างเธรด i nvolves การสื่อสารของเธรดระหว่างกัน สามวิธีที่ใช้ในการปรับใช้การสื่อสารระหว่างเธรดใน Java
รอ()
วิธีนี้ทำให้เธรดปัจจุบันปลดล็อค . การดำเนินการนี้จะทำจนกว่าเวลาที่กำหนดหรือเธรดอื่นเรียก notify() หรือ notifyAll() วิธีการสำหรับวัตถุนี้
แจ้ง()
เมธอดนี้ ปลุกเธรดเดียว จากหลายเธรดบนมอนิเตอร์ของอ็อบเจ็กต์ปัจจุบัน การเลือกเธรดเป็นไปตามอำเภอใจ
notifyAll()
วิธีนี้ ปลุกเธรดทั้งหมด ที่อยู่บนจอภาพของวัตถุปัจจุบัน
ตัวอย่าง
class BankClient {
int balAmount = 5000;
synchronized void withdrawMoney(int amount) {
System.out.println("Withdrawing money");
balAmount -= amount;
System.out.println("The balance amount is: " + balAmount);
}
synchronized void depositMoney(int amount) {
System.out.println("Depositing money");
balAmount += amount;
System.out.println("The balance amount is: " + balAmount);
notify();
}
}
public class ThreadCommunicationTest {
public static void main(String args[]) {
final BankClient client = new BankClient();
new Thread() {
public void run() {
client.withdrawMoney(3000);
}
}.start();
new Thread() {
public void run() {
client.depositMoney(2000);
}
}.start();
}
} ผลลัพธ์
Withdrawing money The balance amount is: 2000 Depositing money The balance amount is: 4000