import java.lang.*;
class Res
{
String name;
String sex;
boolean flag=false;
public synchronized void set(String name,String sex)
{
if(flag)
try
{
this.wait();
}
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 Input implements Runnable
{
private Res r;
public Input(Res r)
{
this.r=r;
}
public void run()
{
int x=0;
while(true)
{
if(x==0)
r.set("lkb","manan");
else
r.set("呵呵","你猜");
x=(x+1)%2;
}
}
}
class Output implements Runnable
{
private Res r;
public Output(Res r)
{
this.r=r;
}
public void run()
{
while(true)
{
r.out();
}
}
}
class InputOutput2
{
public static void main(String[] args)
{
Res r=new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}
java 线程间通信同步代码块
最新推荐文章于 2024-10-09 11:13:12 发布