本帖最后由 zhoubinjian 于 2016-4-4 04:38 编辑
/*
需求:一边录入资源,一边输出资源
加了同步问题还在?
想想前提:1.多线程运行代码是不是都同步了,2.是不是同一个锁
怎么解决资源一直录入,而没有同时打印?
利用等待唤醒机制,成功录入一条资源,唤醒等待,接着输出,成功输出一条资源,唤醒等待
*/
class Res
{
String name;
String sex;
boolean flag=false;
}
class Intput implements Runnable
{
private Res r;
Intput(Res r)//接收同一个资源对象
{
this.r=r;
}
public void run()
{
int x=0;
while(true)//重复传资源进去
{
synchronized(r)
{
if(r.flag) //如果false,不等待
try{r.wait();}catch(Exception e){} //wait()函数是需要抛出异常的
if(x==0)
{
r.name="zhoubin";
r.sex="men";
}
else
{
r.name="lili";
r.sex="women";
}
x=(x+1)%2;//重复1,0
r.flag=true;
r.notify();//表示唤醒r中的锁的wait()
}
}
}
}
class Output implements Runnable
{
private Res r;
Output(Res r)//接收同一个资源对象
{
this.r=r;
}
public void run()
{
while(true)
{
synchronized(r)
{
if(!r.flag) //Intput中flag=true, !r.flag则为false
try{r.wait();}catch(Exception e){}
System.out.println(r.name+"----"+r.sex);
r.flag=false;
r.notify();
}
}
}
}
class Demo
{
public static void main(String[] args)
{
Res r=new Res();
Intput in=new Intput(r);
Output ou=new Output(r);
Thread t1=new Thread(in);
Thread t2=new Thread(ou);
t1.start();
t2.start();
}
}
优化代码:
class Res
{
private String name;
private String sex;
boolean flag=false;
public synchronized void setNum(String name,String sex)
{
if(flag)
{
try{this.wait();}catch(Exception e){}
this.name=name;
this.sex=sex;
}
flag=true;
notify();
}
public synchronized void out()
{
if(!flag)
{
try{this.wait();}catch(Exception e){}
System.out.println(name+"----"+sex);
}
flag=false;
notify();
}
}
class Intput implements Runnable
{
private Res r;
Intput(Res r)
{
this.r=r;
}
public void run()
{
int x=0;
while(true)
{
if(x==0)
r.setNum("zhoubin","men");
else
r.setNum("lili","women");
x=(x+1)%2;
}
}
}
class Output implements Runnable
{
private Res r;
Output(Res r)
{
this.r=r;
}
public void run()
{
while(true)
{
r.out();
}
}
}
class Demo
{
public static void main(String[] args)
{
Res r=new Res();
new Thread(new Intput(r)).start();
new Thread(new Output(r)).start();
/*
Intput in=new Intput(r);
Output ou=new Output(r);
Thread t1=new Thread(in);
Thread t2=new Thread(ou);
t1.start();
t2.start();
*/
}
}
|
|