Java 线程生产者/消费者

2018-02-28 14:26 更新

Java线程教程 - Java线程生产者/消费者


生产者/消费者是使用wait()和notify()方法的典型线程同步问题。

例子

有四个类:缓冲区,生产者,消费者和生产者CumerumerTest。

Buffer类的一个对象具有一个整数数据元素,它将由生产者生成并由消费者消费。

我们必须同步对缓冲区的访问,因此只有当缓冲区为空时,生产者才产生一个新的数据元素,而消费者只有在可用时才消耗缓冲区的数据。

ProducerConsumerTest类用于测试程序。

import java.util.Random;

class Consumer extends Thread {
  private Buffer buffer;

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

  public void run() {
    int data;
    while (true) {
      data = buffer.consume();
    }
  }
}

public class Main {
  public static void main(String[] args) {
    Buffer buffer = new Buffer();
    Producer p = new Producer(buffer);
    Consumer c = new Consumer(buffer);

    p.start();
    c.start();
  }
}

class Producer extends Thread {
  private Buffer buffer;

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

  public void run() {
    Random rand = new Random();
    while (true) {
      int n = rand.nextInt();
      buffer.produce(n);
    }
  }
}

class Buffer {
  private int data;
  private boolean empty;

  public Buffer() {
    this.empty = true;
  }

  public synchronized void produce(int newData) {
    while (!this.empty) {
      try {
        this.wait();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    this.data = newData;
    this.empty = false;
    this.notify();
    System.out.println("Produced:" + newData);
  }

  public synchronized int consume() {
    while (this.empty) {
      try {
        this.wait();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    this.empty = true;
    this.notify();
    System.out.println("Consumed:" + data);
    return data;
  }
}

上面的代码生成以下结果。



以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号