本帖最后由 刘敏 于 2013-12-3 00:03 编辑
class Res
{
String name;
String sex;
boolean flag=false;
}
class Input implements Runnable
{
private Res r;
Input(Res r)
{
this.r=r;
}
public void run()
{
int x=0; //b=true;
while(true)
{ // if(r.flag) --放入同步代码块
// wait();--不能放在这里, 放入同步代码块,wait()函数的要求
synchronized(r)
{
if(r.flag) //--放入同步代码块
try{ r.wait();} catch(Exception e){} //--放入同步代码块,要用唯一资源加锁,默认是this.wait(),不行。要用try包起来
if(x==0) //if(b=ture)
{
r.name="徐成林";
r.sex="男";
//b=false;
}else{
r.name="紫萱";
r.sex="女";
//b=true
}
r.flag=true;//--放入同步代码块
r.notify();//--放入同步代码块,notify()函数的要求,要用唯一资源加锁,默认是this.notify(),不行
}
x=(x+1)%2;
}
}
}
class Output implements Runnable
{
private Res r;
Output(Res r)
{
this.r=r;
}
public void run()
{
while(true)
{
synchronized(r)
{
if(!r.flag)
try{ r.wait();} catch(Exception e){}//同上
System.out.println(r.name+"..."+r.sex);
r.flag=false;//同上,放入同步代码块
r.notify();//同上,放入同步代码块
}
}
}
}
class InputOutputDemo
{
public static void main(String[] args)
{
Res r=new Res();
Input in=new Input(r);
Output out=new Output(r);
Thread t1=new Thread(in);
Thread t2=new Thread(out);
t1.start();
t2.start();
}
}
|