多線程之生產消費

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();

}

}



}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章