睡觉的理发师,null.point.exception [英] Sleeping Barber, null.point.exception
问题描述
你好,
我的睡眠理发师问题代码有问题,现在看了近12个小时,看不出什么错(也许只是一个小错误,我看不到)。
我会很感激,如果有人会看到它,并给我一个关于什么是错误的暗示:)
当我运行程序时,它说:
java.lang.NullPointerException
at BarberShop.barber(BarberShop.java:20 ) - 在BarberShop.run上的wait()方法
(BarberShop.java:64) -
BarberShop.main的
(BarberShop.java:55)
代码可以在这个链接上看到:
Hello,
I have a problem with my Sleeping Barber problem code, and have looked at it for almost 12 hours now, and can't see whats wrong (maybe just a small mistake, that I could't see).
I will appreciate if anyone will look at it, and give me a hint about whats wrong :)
When i run the program, it says:
java.lang.NullPointerException
at BarberShop.barber(BarberShop.java:20) - the wait() method
at BarberShop.run(BarberShop.java:64) -
at BarberShop.main(BarberShop.java:55)
The code can be seen here on this link:
public class BarberShop
{
private Barber barber;
private Customer customer;
private int waiting;
private int chairs;
private boolean isAvailable;
public BarberShop()
{
waiting = 0;
chairs = 5;
}
public void barber()
{
synchronized(this) {
while(true) {
try {
customer.wait();
}
catch (InterruptedException exception) {
}
waiting--;
this.notify();
barber.cutHair();
}
}
}
public void customer()
{
synchronized(this) {
if(waiting < chairs) {
waiting++;
this.notify();
try {
barber.wait();
}
catch (InterruptedException exception) {
}
customer.getHairCut();
}
else {
//shop is full
}
}
}
public static void main(String args[])
{
BarberShop barberShop = new BarberShop();
barberShop.run();
}
public void run()
{
final int barbers = 1;
for(int i = 0 ; i < barbers ; i++) {
barber = new Barber();
barber();
}
int customerID = 1;
while(true) {
customer = new Customer(customerID++);
customer();
// try {
// //sleep();
// }
// catch (InterruptedException exception) {
// }
}
}
}
- Dennis
- Dennis
推荐答案
在初始化customer
对象之前,您正在调用customer.wait()
。由于对对象和方法使用相同的名称,因此理解代码并不容易。
You are callingcustomer.wait()
before the initialisation of thecustomer
object. It is not easy to understand your code owing to the use of the same name for an object and a method.
您没有初始化客户对象到客户参考类型
多数民众赞成为何你得到空指针异常
对于每个对象默认文字是'null'值
初始化您的客户对象然后您的问题将解决
You Are Not Initializing The Customer Object To Customer Reference Type
Thats Why You Are Getting The Null Pointer Exception
For Every Object Default Literal Is 'null' value
Initialize You Customer Object Then Your Problem Will Solve
这篇关于睡觉的理发师,null.point.exception的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!