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来进行的。

 

你可能感兴趣的:(notifyAll)