溫馨提示×

java線程等待如何優雅地進行資源共享

小樊
88
2024-07-09 10:05:29
欄目: 編程語言

在Java中,線程等待通??梢酝ㄟ^使用wait()和notify()方法來實現資源共享。wait()方法用于使當前線程等待并釋放對象的鎖,而notify()方法用于喚醒等待中的線程。下面是一個簡單的示例代碼來展示如何優雅地使用wait()和notify()方法進行資源共享:

public class Resource {
    private int value;
    private boolean isSet = false;

    public synchronized void setValue(int value) {
        while (isSet) {
            try {
                wait();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        this.value = value;
        isSet = true;
        System.out.println("Set value: " + value);
        notify();
    }

    public synchronized int getValue() {
        while (!isSet) {
            try {
                wait();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        isSet = false;
        System.out.println("Get value: " + value);
        notify();
        return value;
    }

    public static void main(String[] args) {
        Resource resource = new Resource();

        Thread producerThread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                resource.setValue(i);
            }
        });

        Thread consumerThread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                resource.getValue();
            }
        });

        producerThread.start();
        consumerThread.start();
    }
}

在上面的示例中,Resource類代表一個共享資源,setValue()方法用于設置值,getValue()方法用于獲取值。在setValue()和getValue()方法中使用了synchronized關鍵字來保證線程安全,并通過wait()和notify()方法來實現線程等待和喚醒。通過這種方式,可以實現線程之間的資源共享和協作。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女