Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Thread สื่อสารกันอย่างไรใน Java

Inter-thread Communication คือการสื่อสารระหว่าง Thread ใช้ 3 เมธอดของ Object (รอใน synchronized block):

1. wait()

Thread ปัจจุบัน ปล่อย Lock และรอ จนกว่า thread อื่นจะเรียก notify() หรือ notifyAll() บนอ็อบเจกต์เดียวกัน หรือครบ timeout

2. notify()

ปลุก Thread เดียว ที่รออยู่บน Monitor ของอ็อบเจกต์นี้ เลือกแบบสุ่ม

3. notifyAll()

ปลุก Thread ทั้งหมด ที่รออยู่บน Monitor ของอ็อบเจกต์นี้

ตัวอย่าง: ธนาคาร ถอน/ฝากเงิน


class BankClient {
    int balance = 5000;
    
    synchronized void withdraw(int amount) {
        System.out.println("Withdrawing money");
        balance -= amount;
        System.out.println("Balance: " + balance);
    }
    
    synchronized void deposit(int amount) {
        System.out.println("Depositing money");
        balance += amount;
        System.out.println("Balance: " + balance);
        notify(); // ปลุก thread ที่รอ
    }
}

public class ThreadCommunicationTest {
    public static void main(String args[]) {
        final BankClient client = new BankClient();
        
        new Thread(() -> client.withdraw(3000)).start();
        new Thread(() -> client.deposit(2000)).start();
    }
}

ผลลัพธ์

Withdrawing money
Balance: 2000
Depositing money
Balance: 4000

สำคัญ: wait/notify/notifyAll ต้องเรียกภายใน synchronized block/method ของอ็อบเจกต์เดียวกัน มิฉะนั้นโยน IllegalMonitorStateException