码迷,mamicode.com
首页 > 编程语言 > 详细

多线程之生产消费

时间:2016-11-22 23:56:36      阅读:237      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!