java線程等待如何優(yōu)雅地進(jìn)行資源共享

小樊
85
2024-07-09 10:05:29

在Java中,線程等待通??梢酝ㄟ^(guò)使用wait()和notify()方法來(lái)實(shí)現(xiàn)資源共享。wait()方法用于使當(dāng)前線程等待并釋放對(duì)象的鎖,而notify()方法用于喚醒等待中的線程。下面是一個(gè)簡(jiǎn)單的示例代碼來(lái)展示如何優(yōu)雅地使用wait()和notify()方法進(jìn)行資源共享:

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類代表一個(gè)共享資源,setValue()方法用于設(shè)置值,getValue()方法用于獲取值。在setValue()和getValue()方法中使用了synchronized關(guān)鍵字來(lái)保證線程安全,并通過(guò)wait()和notify()方法來(lái)實(shí)現(xiàn)線程等待和喚醒。通過(guò)這種方式,可以實(shí)現(xiàn)線程之間的資源共享和協(xié)作。

0