创建生产和消费的对象类
public class Book {
private String name; // 书本名称
private int num = 0; //当前书本的本数
public Book() {
}
public Book(String name, int num) {
this.name = name;
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
生产者类
生产者类实现Runnable接口
public class Producer implements Runnable {
private int count;
Book book;
public Producer(Book book) {
this.book = book;
}
@Override
public void run() {
while (true) {
synchronized (book) {
if (book.getNum() > 0) {
try {
book.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
count++;
book.setNum(count);
System.out.println("生产者" + Thread.currentThread().getName() + "生产" + book.getName() + "本数" + book.getNum());
book.notify();
count = 0;
}
}
}
}
}
锁对象为当前生产的书对象,当书的数量大于0的时候等待消费者消费书本;当书本数量小于等于0本时生产者生产书本并通知消费者消费。
消费者类
public class Consumer implements Runnable {
Book book;
public Consumer() {
}
public Consumer(Book book) {
this.book = book;
}
@Override
public void run() {
while (true) {
synchronized (book) {
if (book.getNum() == 0) {
try {
book.wait(); // 等待生产者生产资源
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
System.out.println("消费者:" + Thread.currentThread().getName() + "消费" + book.getName() + "本数:" + book.getNum());
book.setNum(0); // 消费完资源
book.notify(); // 通知生产者生产资源
}
}
}
}
}
消费者对象判断生产者对象是否生产了书,若生产了书,则消耗书本;反之通知生产者生产并等待生产者生产。
运行类和运行截图
public class ConsumerAndProducerTest {
public static void main(String[] args) {
Book book = new Book("1", 0);
Producer producer = new Producer(book);
Consumer consumer = new Consumer(book);
Thread t1 = new Thread(producer);
Thread t2 = new Thread(consumer);
t1.start();
t2.start();
}
}