首页 > 编程语言 > 详细

多线程之生产消费

时间:2016-11-22 23:54:19      阅读:378      评论:0      收藏:0      [点我收藏+]
package mysd;

public class Main {
	public static void main(String[] args) {
		DianY dy=new DianY();
		ChangJ cj=new ChangJ(dy);
		Xiaof xf=new Xiaof(dy);
		Thread td=new Thread(cj);
		Thread td2=new Thread(cj);
		
		Thread td1=new Thread(xf);
		Thread td11=new Thread(xf);
//		td2.start();
		td.start();
		td1.start();
		td11.start();
		
	}

}



package mysd;


public class DianY {

int top=30;

public synchronized void add(){

if(this.top>=50){

try {

this.wait();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}else{

top++;

System.out.println("生产者生产的"+top+"个产品。");

notifyAll();

}

}

public synchronized void de(){

if(this.top<=0){

try {

this.wait();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}else{

top--;

System.out.println("消费的"+top+"个产品。");

notifyAll();

}

}


}



package mysd;


public class ChangJ implements Runnable{

private DianY dy;

public ChangJ(DianY dy){

this.dy=dy;

}


@Override

public void run() {

for(;;){

try {

Thread.sleep(50);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

dy.add();

}

}


}



package mysd;


public class Xiaof implements Runnable{

private DianY dy;

public  Xiaof(DianY dy) {

// TODO Auto-generated constructor stub

this.dy=dy;

}


@Override

public void run() {

// TODO Auto-generated method stub

for(;;){

try {

Thread.sleep(50);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

dy.de();

}

}



}


多线程之生产消费

原文:http://12013681.blog.51cto.com/12003681/1875551

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!