黑马程序员技术交流社区
标题:
这个线程异常怎么回事儿
[打印本页]
作者:
北冥有鱼
时间:
2014-2-20 13:59
标题:
这个线程异常怎么回事儿
class ThreadTest2
{
public static void main(String[] args)
{
Student st=new Student();
InPut input=new InPut(st);
OutPut output=new OutPut(st);
Thread in=new Thread(input);
Thread out=new Thread(output);
in.start();
out.start();
}
}
class Student
{
String name;
String sex;
Boolean flag=false;
}
class InPut implements Runnable
{
private Student st;
int x=0;
InPut(Student st)
{
this.st=st;
}
public void run()
{
while (true)
{
if (st.flag)
{
try
{
wait();
}
catch (Exception e)
{
}
}else
{
synchronized(Student.class)
{
if (x==0)
{
st.name="zhansan";
st.sex="boy";
}else
{
st.name="lisi";
st.sex="girl";
}
x=(x+1)%2;
}
}
st.flag=true;
notify();
}
}
}
class OutPut implements Runnable
{
private Student st;
OutPut(Student st)
{
this.st=st;
}
public void run()
{
while (true)
{
if (!st.flag)
{
try
{
wait();
}
catch (Exception e)
{
}
}else
{
synchronized(Student.class)
{
System.out.println(st.name+"......"+st.sex);
}
}
st.flag=false;
notify();
}
}
}
作者:
kkopopo
时间:
2014-2-20 14:58
楼主你读读你的程序 你加锁的时候能锁住吗? synchronized(Student.class){}要把while(true){}整体都锁住
要不然就会出现 notify前面有个默认的this 该对象一会锁住,一会没锁住 , JVM 崩溃了!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2