class test1 implements Runnable
{
int able=0;
test3 t3;
public test1(test3 t3)
{
this.t3=t3;
}
public void run()
{
while(true)
{
if(able==0)
{
t3.set("lizhao","man");
able=1;
}
else
{
t3.set("xingyu","male ");
able=0;
}
}
}
}
class test2 implements Runnable
{
test3 t3;
public test2(test3 t3)
{
this.t3=t3;
}
public void run()
{
while(true)
{
t3.get();
}
}
}
class test3
{
String name="no";
String sex="no";
boolean bfull=false;
public synchronized void set(String name,String sex)
{
if(bfull)
{
try
{
wait();
}
catch(Exception ex)
{
}
}
this.name=name;
this.sex=sex;
bfull=true;
notify();
}
public synchronized void get()
{
if(!bfull)
{
System.out.println(!bfull);
try
{
wait();
}
catch(Exception ex)
{
}
}
System.out.println(name+":"+sex);
bfull=false;
notify();
}
}
class test4
{
public static void main(String[] args)
{
test3 t3=new test3();
new Thread(new test1(t3)).start();
new Thread(new test2(t3)).start();
}
}问题是:
在 test3类中的set()方法中,if(bfull)这个括号中的bfull是true还是false ?如果是true,那是因为什么呢?在初始化时定义bfull的值是false呀!如果是true,是不是代表test1线程一开始就执行了wait()方法,进入了等待状态,是吗?
关键看线程的执行先后顺序,先start并不代表一定先被执行,看cpu分配时间
test3 t3=new test3(); //此时bfull=false;
new Thread(new test1(t3)).start(); //如果这个线程先执行,那么t3.set先被调用,此时bfull是false,所以test1不会wait
new Thread(new test2(t3)).start(); //如果这个线程先执行,那么t3.get先被调用,此时bfull是false,所以test2会wait另外,notify是唤醒单个线程,用notifyAll唤醒所有等待线程好一些