管理员
public class Admin {
private int product=0;
public synchronized void addProduct() {
if(product>=20) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
product++;
System.out.println("生产者生产了"+product+"产品");
notify();
}
}
public synchronized void getProduct() {
if(product<=0) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
product--;
System.out.println("消费者消费了,还有"+product+"个产品");
notify();
}
}
}
管理员定义两个方法生产者方法和消费者方法,并且使两个方法同步。
生产者
public class Productor implements Runnable{
Admin admin;
public Productor(Admin admin) {
this.admin=admin;
}
@Override
public void run() {
System.out.println("开始生产");
while(true) {
try {
Thread.sleep((int)Math.random()*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
admin.addProduct();
}
}
}
生产者实现Runnable接口,重写run()方法。
消费者
public class Consumer implements Runnable{
Admin admin;
public Consumer(Admin admin) {
this.admin=admin;
}
@Override
public void run() {
System.out.println("消费者消费了");
while(true) {
try {
Thread.sleep((int)Math.random()*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
admin.getProduct();
}
}
}
测试用例
public class ProductTest {
public static void main(String[] args) {
Admin a=new Admin();
Thread productThread=new Thread(new Productor(a));
Thread consumerThread=new Thread(new Consumer(a));
productThread.start();
consumerThread.start();
}
}