class Res
{
String name;
String sex;
boolean flag = false;
}
class Input implements Runnable
{
private Res r;
Object obj = new Object();
Input(Res r)
{
this.r = r;
}
public void run()
{
boolean b = true;
while (true)
{
synchronized (r)
{
if (r.flag) //flag的初始值不是false么,那么共享资源中应该没有数据,Input线程应该向下执行往共享资源中添加数据才对,怎么会是等待呢?
{
try {
r.wait();
} catch (Exception e) {
}
}
if (b)
{
r.name = "mike";
r.sex = "man";
b = false;
}
else
{
r.name = "丽丽";
r.sex = "女女女女";
b = true;
}
r.flag = true;
r.notify();
}
}
}
}
class Output implements Runnable
{
private Res r;
Object obj = new Object();
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();
}
}
}
}
public class Demo
{
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();
}
}
以上代码是老毕多线程-等待唤醒机制中的代码
因为有以上的疑惑,所以我自己写了个代码测试了下,
class MyTest1
{
public static void main(String[] args)
{
Boolean flag = true;
if(flag)
System.out.println("1"); //执行这条语句,输出结果是1
else if(!flag)
System.out.println("2");
else
System.out.println("3");
}
}
class MyTest2
{
public static void main(String[] args)
{
Boolean flag = false;
if(flag)
System.out.println("1");
else if(!flag)
System.out.println("2"); //执行这条语句,输出结果是2
else
System.out.println("3");
}
}
为什么MyTest2中执行的是第二条语句,输出了2?求解释。 |
|