当前位置:首页 > 开发 > 编程语言 > 多线程 > 正文

4个线程,2个每次加1,两个每次减1

发表于: 2014-09-01   作者:annan211   来源:转载   浏览:
摘要: package threadTest; public class MultiThreadShareDemo { public static void main(String[] args) throws Exception { Data data = new Data(); Plus p = new Plus(data); Cut c = new Cut
package threadTest;

public class MultiThreadShareDemo {

	public static void main(String[] args) throws Exception {

		Data data = new Data();

		Plus p = new Plus(data);
		Cut c = new Cut(data);

		Thread t1 = new Thread(p);
		Thread t2 = new Thread(p);

		Thread t3 = new Thread(c);
		Thread t4 = new Thread(c);

		t1.start();
		t2.start();
		t3.start();
		t4.start();

	}
}

/**
 * 数据包装
 * @author jingfn
 *
 */
 class Data{
	 private int data;
	 private boolean flag;
	 private int count = 2;

	public synchronized Data plus(Data dataIns){
		while(flag){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		dataIns.data = dataIns.data - 1;
		dataIns.count = dataIns.count - 1;
		System.out.println(Thread.currentThread().getName()+"--plus--------"+dataIns.data+"---"+dataIns.count);
		if(dataIns.count <= 0){
			dataIns.flag = true;
			this.notifyAll();
		}
		return dataIns;
	}

	public synchronized Data cut(Data dataIns){
		while(!flag){
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		dataIns.data = dataIns.data + 1;
		dataIns.count = dataIns.count + 1;
		System.out.println(Thread.currentThread().getName()+"--cut--"+dataIns.data+"---"+dataIns.count);
		if(dataIns.count >= 2){
			dataIns.flag = false;
			this.notifyAll();
		}
		return dataIns;
	}

 }

 /**
  * 加线程
  * @author jingfn
  *
  */
 class Plus implements  Runnable {
	 private Data instance;
	 public Plus(Data instance){
		 this.instance = instance;
	 }
	 public void run(){
		 while(true){
			 instance.plus(instance);
		 }
	 }
 }

 /**
  * 减线程
  * @author jingfn
  *
  */
 class Cut implements  Runnable {
	 private Data instance;
	 public Cut(Data instance){
		 this.instance = instance;
	 }
	 public void run(){
		 while(true){
			 instance.cut(instance);
		 }
	 }
 }

4个线程,2个每次加1,两个每次减1

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号