您的位置:首页 > 其它

线程间通信--等待唤醒机制

2013-09-29 19:36 513 查看
//线程间通信--等待唤醒机制
class Res
{
	String name;
	String sex;
	boolean flag = false;
	
}
class Input implements Runnable
{
	private Res r; 
	Input(Res r)
	{
		this.r = r;
	}
	public void run()
	{
		int x = 0;
		while(true)
		{
			synchronized(r)
			{
				if(r.flag)
					try{r.wait();}catch(Exception e){}
				if(x==0)
				{
					r.name="mike";
					r.sex = "man";
				}
				else
				{
					r.name ="丽丽";
					r.sex = "女女女";
				}
				x=(x+1)%2;
				r.flag=true;
				r.notify();
			}
		}
	}
}
class Output implements Runnable
{
	private Res r;
	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();
			}
		}
	}
}

class ThreadDemo
{
	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();
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐