码迷,mamicode.com
首页 > 编程语言 > 详细

java 线程三

时间:2016-05-12 20:57:40      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

线程间的通信问题。

注意同步的前提:
1,有两个或两个以上的线程
2,用同一个锁

wait()
notify()
notifyAll()
以上方法都是定义在Object类中的方法。
都使用在同步中,因为要对持有监视器(加锁)的线程操作。
所以要使用在同步中,因为只有同步才会有锁。
为什么这些操作线程的方法要定义在Object类中呢?
因为这些方法在操作同步中线程时,都必须要标识他们操作线程只有的锁,
只有同一个锁上的被等待线程,可以被同一个锁上notify唤醒。
不可以对不同锁上的线程进行唤醒。

也就是说线程等待和唤醒必须是同一个锁。

而锁可以是任意对象,所以可以被任意对象调用的方法定义在Object类中。
*/
//此为优化过的代码。
class Res
{
	private String name;
	private 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;
	Object obj=new Object();
	Input(Res r)
	{
		this.r=r;
	}
	public void run()
	{
		int x=0;
		while(true)
		{
				if(x==0)
					r.set("jhon","man");
				else
					r.set("li......","women......");
				x=(x+1)%2;
		}
	}
}

class Output implements Runnable
{
	private Res r;
	Output(Res r)
	{
		this.r=r;
	}
	public void run()
	{
		while(true)
		{
				r.out();
		}
	}
}

class  InputOutputDemo1
{
	public static void main(String[] args) 
	{
		Res r=new Res();
		
		new Thread(new Input(r)).start();
		new Thread(new Output(r)).start();

		/*
		Input in=new Input(r);
		Output out=new Output(r);

		Thread t1=new Thread(in);
		Thread t2=new Thread(out);

		t1.start();
		t2.start();
	    */
		System.out.println("Hello World!");
	}
}

java 线程三

标签:

原文地址:http://blog.csdn.net/iemdm1110/article/details/51357060

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!