首页 > 代码库 > 多线程之生产消费
多线程之生产消费
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();
}
}
}
多线程之生产消费