java多線程怎么實(shí)現(xiàn)生產(chǎn)者消費(fèi)者模式

小樊
83
2024-09-02 05:24:19

在Java中,可以使用wait()notify()notifyAll()方法來實(shí)現(xiàn)生產(chǎn)者-消費(fèi)者模式。這些方法是Object類的一部分,用于線程間的通信。下面是一個(gè)簡(jiǎn)單的生產(chǎn)者-消費(fèi)者模式示例:

  1. 首先,創(chuàng)建一個(gè)共享資源類,例如一個(gè)緩沖區(qū)(Buffer):
public class Buffer {
    private int data;
    private boolean empty = true;

    public synchronized void put(int data) {
        while (!empty) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.data = data;
        empty = false;
        notifyAll();
    }

    public synchronized int get() {
        while (empty) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        empty = true;
        notifyAll();
        return data;
    }
}
  1. 創(chuàng)建生產(chǎn)者線程類:
public class Producer implements Runnable {
    private Buffer buffer;

    public Producer(Buffer buffer) {
        this.buffer = buffer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("Produced: " + i);
            buffer.put(i);
        }
    }
}
  1. 創(chuàng)建消費(fèi)者線程類:
public class Consumer implements Runnable {
    private Buffer buffer;

    public Consumer(Buffer buffer) {
        this.buffer = buffer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            int data = buffer.get();
            System.out.println("Consumed: " + data);
        }
    }
}
  1. 在主程序中創(chuàng)建生產(chǎn)者和消費(fèi)者線程,并啟動(dòng)它們:
public class Main {
    public static void main(String[] args) {
        Buffer buffer = new Buffer();
        Thread producerThread = new Thread(new Producer(buffer));
        Thread consumerThread = new Thread(new Consumer(buffer));

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

運(yùn)行上述代碼,你將看到生產(chǎn)者和消費(fèi)者線程交替執(zhí)行,生產(chǎn)者將數(shù)據(jù)放入緩沖區(qū),消費(fèi)者從緩沖區(qū)中取出數(shù)據(jù)。這就是一個(gè)簡(jiǎn)單的生產(chǎn)者-消費(fèi)者模式實(shí)現(xiàn)。

0