//同学你好,我修改你的代码后实现了你的要求
class Res
{
static String Name = "李斯";
static String Sex = "男";
static boolean flag = false;
static Object obj = new Object();
}
class Input implements Runnable
{
public void run()
{
for(int x=0; x < 10; x++)
{
synchronized(Res.obj)
{
//if(Res.flag)
while(Res.flag) //这里应该使用while(),这样可以使线程每次被唤醒后都会去检查Res.flag值
{
try{Res.obj.wait();}catch(Exception e){}
}
if(x%2 == 0)
{
Res.Name = "麦克。。。。";
Res.Sex = "M男。。。。。。。。。";
}
else
{
Res.Name = "Lily";
Res.Sex = "Female";
}
Res.flag = true; //这里修改为true,因为必须要让这个线程执行一遍后wait
Res.obj.notifyAll();
}
}
}
}
class Output implements Runnable
{
public void run()
{
synchronized(Res.obj)
{
for(int i = 0; i < 10 ; i++)
{
//if(!Res.flag)
while(!Res.flag) //这里使用(!Res.flag)取反来调节线程运行
{
try{Res.obj.wait();}catch(Exception e){}
}
System.out.println(Res.Name+"....."+Res.Sex);
Res.flag = false;
Res.obj.notifyAll();
}
}
}
}
public class Demo2
{
public static void main(String args[])
{
Input input = new Input();
Output output = new Output();
Thread t1 = new Thread(input);
Thread t2 = new Thread(output);
t1.start();
t2.start();
}
}
写while循环进行判断是因为线程等待后在此被唤醒会继续它上次的操作继续运行,这样会出现问题,
循环的在让这个线程在判断一次就不会出先错误了,
赋值的任务中没赋值完应该让标识该成true然后判断到true是该线程等待,让输出的线程来执行,输
出线程执行完后在将标识符该为false,在去唤醒等待的赋值线程,如此交替进行,就可以实现你想要
达到的目的了
|