首页 > 代码库 > java的wait和notifyAll用法

java的wait和notifyAll用法

class Num{	private int num;	public int getNum() {		return num;	}	public void setNum(int num) {		this.num = num;	}	public Num(int num)	{		this.num=num;	}}class myThreadA extends Thread{	private Num num;	public myThreadA(Num num)	{		this.num=num;	}		public void run()	{			while(true)			{				synchronized(num)				{					while(num.getNum()!=1)						try {							num.wait();						} catch (InterruptedException e) {							// TODO Auto-generated catch block							e.printStackTrace();						}										System.out.println(1);					num.setNum(2);					num.notifyAll();				}			}				}}class myThreadB extends Thread{	private Num num;	public myThreadB(Num num)	{		this.num=num;	}		public void run()	{			while(true)			{				synchronized(num)				{					while(num.getNum()!=2)						try {							num.wait();						} catch (InterruptedException e) {							// TODO Auto-generated catch block							e.printStackTrace();						}										System.out.println(2);					num.setNum(1);					num.notifyAll();				}			}				}}public class test001 {	/**	 * @param args	 */	public static void main(String[] args) {		// TODO Auto-generated method stub		Num num=new Num(1);		myThreadA a=new myThreadA(num);		myThreadB b=new myThreadB(num);		a.start();		b.start();			}}


代码如上所示

输出内容如下

2
1
2
1
2
1

 

 

即反复输出1和2.这里我们就采用了线程的同步模式,一个线程输出1,另外一个线程输出2,并且能够进行同步,同步则是利用对象Num的wait和notifyAll来进行的。

 

java的wait和notifyAll用法