黑马程序员技术交流社区
标题:
同步代码块中wait()方法放在里面和外面有什么不同
[打印本页]
作者:
黑马-许鹏
时间:
2013-5-11 15:33
标题:
同步代码块中wait()方法放在里面和外面有什么不同
在多线程技术中,如果两个(或多个)线程对共同数据资源做不同操作,为了保持数据同步性,要调用线程的等待和唤醒操作。如果把wait()方法用在synchronized外面则会出现数据错误。请问是为什么呢?
/*
线程间的通信,两个线程对同一个数据做不同操作的安全问题
*/
class src
{
public boolean flag=true;
String name;
String sex;
}
class Input implements Runnable
{
private src s;
public Input(src s)
{
this.s=s;
}
public void run()
{
int x=0;
while(true)
{
synchronized(s)
{
if(!s.flag)
try
{
s.wait();
}
catch (Exception e)
{
}
if(x==0)
{
s.name="张三";
s.sex="男";
x=1;
}
else
{
s.name="李思";
s.sex="女";
x=0;
}
s.flag=false;
s.notify();
}
}
}
}
class Output implements Runnable
{
private src s;
public Output(src s)
{
this.s=s;
}
public void run()
{
while(true)
{
synchronized(s)
{
if(s.flag)
try
{
s.wait();
}
catch (Exception e)
{
}
System.out.println("姓名:"+s.name+"……性别:"+s.sex);
s.flag=true;
s.notify();
}
}
}
}
class InputOutputDemo
{
public static void main(String[] args)
{
src s=new src();
Input in=new Input(s);
Output out=new Output(s);
Thread t1=new Thread(in);
Thread t2=new Thread(out);
t1.start();
t2.start();
}
}
复制代码
如果把代码改成这样:
/*
线程间的通信,两个线程对同一个数据做不同操作的安全问题
*/
class src
{
public boolean flag=true;
String name;
String sex;
}
class Input implements Runnable
{
private src s;
public Input(src s)
{
this.s=s;
}
public void run()
{
int x=0;
while(true)
{
if(!s.flag)
try
{
s.wait();
}
catch (Exception e)
{
}
synchronized(s)
{
if(x==0)
{
s.name="张三";
s.sex="男";
x=1;
}
else
{
s.name="李思";
s.sex="女";
x=0;
}
s.flag=false;
s.notify();
}
}
}
}
class Output implements Runnable
{
private src s;
public Output(src s)
{
this.s=s;
}
public void run()
{
while(true)
{
if(s.flag)
try
{
s.wait();
}
catch (Exception e)
{
}
synchronized(s)
{
System.out.println("姓名:"+s.name+"……性别:"+s.sex);
s.flag=true;
s.notify();
}
}
}
}
class InputOutputDemo
{
public static void main(String[] args)
{
src s=new src();
Input in=new Input(s);
Output out=new Output(s);
Thread t1=new Thread(in);
Thread t2=new Thread(out);
t1.start();
t2.start();
}
}
复制代码
这样会出现数据存取错误。请问原因?
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2