以下为主要类
package b;
/**
* @author 真他喵的学不动咯
* @create 2022-08-03--19:47
*/
public class Productor {
//属性
private int num;
private int i;
//getter&&setter
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
//构造器
public Productor(int num){
this.num=num;
}
//方法
public void pro(){
while(true){
if(getNum()<num){
i++;
setNum(i);
System.out.println("生产产品第"+i+"个"+"此时的产品总数为:"+getNum());
}
else{
break;
}
}
}
}
package b;
/**
* @author 真他喵的学不动咯
* @create 2022-08-03--19:53
*/
public class Clerk implements Runnable{
//属性
private Productor p1;
private Customer c1;
//构造器
//无需构造器
//方法
@Override
public void run() {
while(true){
synchronized(this) {
//给消费者的代码
this.notify();
if (p1.getNum()!=0) {
c1.cust();//如果产品数量不是0,那就让他消费
}
else {
try {
this.wait();//如果产品数量是0,那就让他别消费了
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//给生产者的代码
this.notify();
if (p1.getNum() < 20) {
p1.pro();//如果产品数量<20,那就让他生产
} else {
try {
this.wait();//如果产品数量不是20,那就让他生产
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
package b;
/**
* @author 真他喵的学不动咯
* @create 2022-08-03--19:59
*/
public class Customer {
//属性
Productor p1;
int i;
//方法
public void cust(){
while (true){
if (p1.getNum()!=0){
i=p1.getNum();
i--;
p1.setNum(i);
System.out.println("消费第"+i+"个产品,"+"剩余产品为"+p1.getNum());
}
}
}
}
以下为测试类
package b;
/**
* @author 真他喵的学不动咯
* @create 2022-08-03--20:04
*/
public class Test {
public static void main(String[] args){
Clerk c1=new Clerk();
Customer Cu1=new Customer();
Productor p1=new Productor(20);
Thread t1=new Thread(c1);
Thread t2=new Thread(c1);
Thread t3=new Thread(c1);
t1.setName("消费者1");
t2.setName("消费者2");
t3.setName("消费者3");
t1.start();
t2.start();
t3.start();
}
}
错误信息:
Exception in thread "消费者1" Exception in thread "消费者2" Exception in thread "消费者3" java.lang.NullPointerException
at b.Clerk.run(Clerk.java:22)
at java.lang.Thread.run(Thread.java:748)
java.lang.NullPointerException
at b.Clerk.run(Clerk.java:22)
at java.lang.Thread.run(Thread.java:748)
java.lang.NullPointerException
at b.Clerk.run(Clerk.java:22)
at java.lang.Thread.run(Thread.java:748)