Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cơ chế giao tiếp giữa các thread trong Java (wait, notify, notifyAll)

Inter-thread Communication

Ba phương thức của Object (không phải Thread) dùng trong synchronized block:

  • wait() – thread hiện tại **nhả lock** và chờ đến khi bị notify hoặc timeout.
  • notify() – **thức dậy một** thread đang wait trên object này (tuỳ scheduler).
  • notifyAll() – **thức dậy tất cả** thread đang wait trên object này.

Phải gọi trong synchronized block/method, ném IllegalMonitorStateException nếu không.

Ví dụ: Producer-Consumer đơn giản (BankClient)


class BankClient {
    int balance = 5000;

    synchronized void withdraw(int amount) {
        System.out.println("Rút tiền: " + amount);
        balance -= amount;
        System.out.println("Số dư: " + balance);
    }

    synchronized void deposit(int amount) {
        System.out.println("Nạp tiền: " + amount);
        balance += amount;
        System.out.println("Số dư: " + balance);
        notify(); // Thức dậy thread đang wait (nếu có)
    }
}

public class ThreadCommunicationDemo {
    public static void main(String[] args) {
        BankClient client = new BankClient();

        new Thread(() -> client.withdraw(3000), "Withdraw-Thread").start();
        new Thread(() -> client.deposit(2000), "Deposit-Thread").start();
    }
}

Kết quả (có thể thay đổi thứ tự do scheduling)

Rút tiền: 3000
Số dư: 2000
Nạp tiền: 2000
Số dư: 4000

Mẫu Producer-Consumer chuẩn với wait/notify


class SharedBuffer {
    private int data;
    private boolean hasData = false;

    synchronized void produce(int value) throws InterruptedException {
        while (hasData) wait(); // chờ consumer lấy
        data = value;
        hasData = true;
        System.out.println("Produced: " + value);
        notifyAll();
    }

    synchronized int consume() throws InterruptedException {
        while (!hasData) wait(); // chờ producer đưa
        hasData = false;
        System.out.println("Consumed: " + data);
        notifyAll();
        return data;
    }
}

Khuyến nghị: Java 5+ nên dùng java.util.concurrent (BlockingQueue, Semaphore, CountDownLatch, CompletableFuture...) thay vì wait/notify thủ công.