实体
//教材
public class Book {
private int id;
public Book(int id) {
this.id = id;
}
@Override
public String toString() {
return "教材" + id;
}
}
仓库
public class ChangKu {
//仓库大小
private int index = 0;
Book[] booklist = new Book[10];
//同步入库
public synchronized void put(Book book) {
if (index >= 9) {
try {
System.out.println("仓库满了,等待取教材");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
booklist[index] = book;
index++;
this.notify();
}
//同步出库
public synchronized Book get() {
if (index == 0) {
try {
System.out.println("仓库空了,等待存教材");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Book book = booklist[--index];
this.notify();
return book;
}
}
生产者
import java.util.Random;
public class Producer implements Runnable {
ChangKu ck = null;
public Producer(ChangKu ck) {
this.ck = ck;
}
public void run() {
while (true) {
Book book = new Book((int) (Math.random() * 1000));
ck.put(book);
System.out.println("放入:" + book);
}
}
}
消费者
public class Consumer implements Runnable {
ChangKu ck = null;
public Consumer(ChangKu ck) {
this.ck = ck;
}
public void run() {
while (true) {
Book book = ck.get();
System.out.println("ȡ��取出" + book);
}
}
}
测试
public class TestPC {
public static void main(String[] args) {
ChangKu ck = new ChangKu();
Producer pd = new Producer(ck);
Consumer cs = new Consumer(ck);
//生成线程
Thread producer = new Thread(pd);
//消费线程
Thread consumer = new Thread(cs);
producer.setName("put");
consumer.setName("get");
producer.start();
consumer.start();
}
}