本帖最后由 李健09 于 2013-8-9 15:07 编辑
毕老师的课件里面的 线程间通信
package com.InOut;
//InputOutputDemo.java 代码优化
class ResYouHua
{
private String name;
private String sex;
private boolean flag=false;
public synchronized void set(String name,String sex)
{
if(flag)
try{this.wait();}//此时的锁是this
catch(Exception e){}
this.name=name;
this.sex=sex;
flag=true;
this.notify();
}
public synchronized void out()
{
if(!flag)
try{this.wait();}
catch(Exception e){}
System.out.println(name+"..."+sex);
flag=false;
this.notify();
}
}
class InputYouHua implements Runnable
{
private ResYouHua r;//资源私有化
InputYouHua(ResYouHua r)//初始化资源
{
this.r=r;
}
public void run()
{
int x=0;
while(true)
{
if(x==0)
r.set("mike","man");
else
r.set("丽丽","女");
x=(x+1)%2;
}
}
}
class OutputYouHua implements Runnable
{
private ResYouHua r;
OutputYouHua(ResYouHua r)//初始化资源
{
this.r=r;
}
public void run()
{
while(true)
{
r.out();
}
}
}
public class YouHuaInputOutputDemo
{
public static void main(String[] args)
{
ResYouHua r=new ResYouHua();//建立资源
new Thread(new InputYouHua(r)).start();
new Thread(new OutputYouHua(r)).start();
}
}
-----------------------------------------------------------------
private boolean flag=false;
if(flag)
try{this.wait();}//此时的锁是this
catch(Exception e){}
this.name=name;
this.sex=sex;
flag=true;
this.notify();//问?此时if里面的初始值是false? 我理解的是false而后执行this.name=name; this.sex=sex;语句返回true 而后停止开始等待, 而后this.notify();唤醒此时的if里面的又是?呢
请帮忙解释下 转不过来了
---------------------------------------
if(!flag)
try{this.wait();}
catch(Exception e){}
System.out.println(name+"..."+sex);
flag=false;
this.notify();//问?此时if里面的初始值是? 前后语句执行的顺序是?
我现在就是搞不明白这个标记是怎么判断的了
|