Java多线程中notify和wait的问题_JAVA_编程开发_程序员俱乐部

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

Java多线程中notify和wait的问题

 2015/5/4 21:45:18  hopana  程序员俱乐部  我要评论(0)
  • 摘要:程序功能:4个线程,2个线程对某个数值进行加1;2个线程进行减1,要求该数在0和1之间切换。程序如下,大家看看问题出在哪里:DecThread类,对sample的i进行减1的线程:publicclassDecThreadextendsThread{privateSamplesample;publicDecThread(Samplesample,Stringname){super(name);this.sample=sample;}@Overridepublicvoidrun(){for
  • 标签:多线程 not Java 问题 线程
程序功能:4个线程,2个线程对某个数值进行加1;2个线程进行减1,要求该数在0和1之间切换。程序如下,大家看看问题出在哪里:

DecThread类,对sample的i进行减1的线程:
class="java">
public class DecThread extends Thread{
	private Sample sample;
	
	public DecThread(Sample sample, String name){
		super(name);
		this.sample = sample;
	}

	@Override
	public void run() {
		for(int i=0; i<20; i++){
			sample.dec();
		}
	}
	
}


IncThread 类,对sample的i进行加1的线程:
public class IncThread extends Thread{
	private Sample sample;

	public IncThread(Sample sample, String name){
		super(name);
		this.sample = sample;
	}

	@Override
	public void run() {
		for(int i=0; i<20; i++){
			sample.inc();
		}
	}
	
}


Sample类:
public class Sample {
	int i = 0;

	public synchronized void inc() {
		try {
			while (i == 1) {
				wait();
			}

			i++;

			System.out.println(Thread.currentThread().getName() + "-" + i);

			notify();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

	public synchronized void dec() {

		try {
			while (i == 0) {
				wait();
			}

			i--;

			System.out.println(Thread.currentThread().getName() + "-" + i);

			notify();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

}


测试类TestIncDec :
public class TestIncDec {
	public static void main(String[] args) {
		Sample sample = new Sample();
		
		IncThread inc1 = new IncThread(sample,"inc1");
		IncThread inc2 = new IncThread(sample,"inc2");
		
		DecThread dec1 = new DecThread(sample,"dec1");
		DecThread dec2 = new DecThread(sample,"dec2");
		
		inc1.start();
		inc2.start();
		dec1.start();
		dec2.start();
	}
}
上一篇: 马云可能会免费送你电视机! 下一篇: 没有下一篇了!
  • 相关文章
发表评论
用户名: 匿名