Java

java多线程怎么实现生产者消费者模式

小樊
83
2024-09-02 05:24:19
栏目: 编程语言

在Java中,可以使用wait()notify()notifyAll()方法来实现生产者-消费者模式。这些方法是Object类的一部分,用于线程间的通信。下面是一个简单的生产者-消费者模式示例:

  1. 首先,创建一个共享资源类,例如一个缓冲区(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. 创建生产者线程类:
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. 创建消费者线程类:
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. 在主程序中创建生产者和消费者线程,并启动它们:
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();
    }
}

运行上述代码,你将看到生产者和消费者线程交替执行,生产者将数据放入缓冲区,消费者从缓冲区中取出数据。这就是一个简单的生产者-消费者模式实现。

0
看了该问题的人还看了