在看毕老师的Java基础视频,看到多线程这块,看完视频后自己敲代码,编译通过,运行的时候抛空指针,对照毕老师的源码一句句对照,除了类名和函数名略有不同之外,没有找到其他不同,百撕不得骑姐,求助大神指点。
我自己敲的
class Person
{
private String name;
private String sex;
private boolean flag=false;
public synchronized void set(String name,String sex)
{
if(flag)
try
{
this.wait();
}
catch (InterruptedException e)
{
}
this.name=name;
this.sex=sex;
flag=true;
this.notify();
}
public synchronized void get()
{
if(!flag)
try
{
this.wait();
}
catch (InterruptedException e)
{
}
System.out.println(name+"..........."+sex);
flag=false;
notify();
}
}
class Input implements Runnable
{
Person p;
Input(Person p)
{
this.p=p;
}
public void run()
{
int x=0;
while(true)
{
if(x==0)
{
p.set("张三","男");
}
else
{
p.set("lily","women");
}
x=(x+1)%2;
}
}
}
class Output implements Runnable
{
Person p;
Output(Person P)
{
this.p=p;
}
public void run()
{
while(true)
{
p.get();//74行报错。
}
}
}
class Wait
{
public static void main(String[] args)
{
Person p=new Person();
Input a=new Input(p);
Output b=new Output(p);
Thread t1=new Thread(a);
Thread t2=new Thread(b);
t1.start();
t2.start();
}
}
错误代码
Exception inthread "Thread-1" java.lang.NullPointerException
at Output.run(Wait.java:74)
at java.lang.Thread.run(Thread.java:744)
毕老师的
class Resource
{
private String name;
private String sex;
private boolean flag = false;
public synchronized void set(String name,String sex)
{
if(flag)
try{this.wait();}catch(InterruptedException e){}
this.name = name;
this.sex = sex;
flag = true;
this.notify();
}
public synchronized void out()
{
if(!flag)
try{this.wait();}catch(InterruptedException e){}
System.out.println(name+"...+...."+sex);
flag = false;
notify();
}
}
//输入
class Input implements Runnable
{
Resource r ;
// Object obj = new Object();
Input(Resource r)
{
this.r = r;
}
public void run()
{
int x = 0;
while(true)
{
if(x==0)
{
r.set("mike","nan");
}
else
{
r.set("丽丽","女女女女女女");
}
x = (x+1)%2;
}
}
}
//输出
class Output implements Runnable
{
Resource r;
// Object obj = new Object();
Output(Resource r)
{
this.r = r;
}
public void run()
{
while(true)
{
r.out();
}
}
}
class ResourceDemo3
{
public static void main(String[] args)
{
//创建资源。
Resource r = new Resource();
//创建任务。
Input in = new Input(r);
Output out = new Output(r);
//创建线程,执行路径。
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
//开启线程
t1.start();
t2.start();
}
}
|
|