Java多线程wait,notify实例_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Java多线程wait,notify实例

Java多线程wait,notify实例

 2013/10/25 12:53:18  alleni123  程序员俱乐部  我要评论(0)
  • 摘要:packagecom.lj.thread2;publicclassSample{privateintnumber;//实现number加1publicsynchronizedvoidincrease(){while(0!=number){try{wait();}catch(InterruptedExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}number++;System.out.println
  • 标签:多线程 not Java 实例 线程
class="java" name="code">package com.lj.thread2;

public class Sample  
{
	private int number;

	// 实现number加1
	public synchronized void increase()
	{
		while (0 != number)
		{
			try
			{
				wait();
			}
			catch (InterruptedException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		number++;
		
		System.out.println("number increased by "+Thread.currentThread().getName()+", number= "+ number);;
		notify();

	}
	
	
	public synchronized void decrease(){
		while(0==number){
			try
			{
				wait();
			}
			catch (InterruptedException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		number--;
		System.out.println("number decreased by "+Thread.currentThread().getName()+", number= "+ number);;
		
		notify();
	}
	
	
	
}



这里定义了对象类, 实现数字在1和0之间进行不停的转换。


package com.lj.thread2;

public class IncreaseThread extends Thread
{
	private Sample sample;
	
	public IncreaseThread(Sample sample){
		this.sample=sample;
	}
	
	
	
	@Override
	public void run()
	{
		for(int i=0;i<20;i++){
			try
			{
				Thread.sleep(1000);
			}
			catch (InterruptedException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			sample.increase();
		}
		
	}
}

对数字加1的线程.

package com.lj.thread2;

public class DecreaseThread extends Thread
{
private Sample sample;
	
	public DecreaseThread(Sample sample){
		this.sample=sample;
	}
	
	
	
	@Override
	public void run()
	{
		for(int i=0;i<20;i++){
			try
			{
				Thread.sleep(1000);
			}
			catch (InterruptedException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			sample.decrease();
		}
		
	}
}





减1的线程


package com.lj.thread2;

public class Test
{
	public static void main(String[] args)
	{	
		Sample s=new Sample();
		Thread increase=new IncreaseThread(s);
		Thread decrease=new DecreaseThread(s);
		
		Thread i2=new IncreaseThread(s);
		Thread d2=new DecreaseThread(s);
		increase.start();
		i2.start();
		decrease.start();
		
		
		d2.start();
	}
}




这里的重点就是while循环那里不能写if。因为一个线程如果处于wait阶段,当它wait结束的时候, 要运行的时候必须再验证一下condition是否符合。
使用if的话不会去进行验证, 会直接执行number++或者number--, 导致错误
发表评论
用户名: 匿名