- 运行时可能出现先消费在生产的情况,这是由于输出没跟上的结果,其内部运行结构是正确的。
- 在进行等待时不要用if判断,而是要用while循环进行判断。
public class P_CTest {
public static void main(String[] args) {
BufferSpace bf=new BufferSpace();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(new Product_er("1号--生产者",bf)).start();
new Thread(new Product_er("2号--生产者",bf)).start();
new Thread(new Custom_er("1号--消费者",bf)).start();
new Thread(new Custom_er("2号--消费者",bf)).start();
}
}
class Product_er implements Runnable{
private String id;
BufferSpace bf;
Product_er(String id,BufferSpace bf) {
this.id = id;
this.bf=bf;
}
@Override
public void run() {
for (int i = 1; i <= 50; i++) {
bf.sell(new Product(i));
System.out.println(id+"生产了产品,ID-->"+i);
}
}
}
class Custom_er implements Runnable{
private String id;
private BufferSpace bf;
Custom_er(String id,BufferSpace bf) {
this.id = id;
this.bf= bf;
}
@Override
public void run() {
for (int i = 0; i < 50; i++) {
System.out.println(id+"消费了产品,ID-->"+bf.buy().getID());
}
}
}
class Product{
private int ID;
Product(int id) {
ID = id;
}
public int getID(){
return ID;
}
}
class BufferSpace{
private int count=0;
private Product[] pro =new Product[5];
public synchronized void sell(Product p){
while(count==5){
try {
System.out.println("货满了,正在等待消费者消费!");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
pro[count++]=p;
this.notifyAll();
return;
}
public synchronized Product buy(){
while (count==0){
try {
System.out.println("货没了,正在等待生产者生产!");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count--;
this.notifyAll();
return pro[count];
}
}