标签:
public class Jz extends Thread {
private String name;
private PanZi p;
public Jz(){
}
public Jz(PanZi p,String name){
this.p=p;
this.name=name;
}
@Override
public void run() {
// TODO 自动生成的方法存根
int sum=1;
while(true){
synchronized(this.p){ //同步方法 坏处效率降低
if(this.p.getP()==0){
break;
}
this.p.setP(this.p.getP()-1);
System.out.println(this.name + "吃了"+ sum +"个饺子");
sum ++;
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
}
}
//公用一个盘子
public class PanZi {
private int p=25;
public int getP() {
return p;
}
public void setP(int p) {
this.p = p;
}
}
//main方法
public class People {
public static void main(String [] args){
PanZi p = new PanZi();
Jz jz1 = new Jz(p,"张三");
Jz jz2 = new Jz(p,"王麻子");
jz1.start();
jz2.start();
}
}
标签:
原文地址:http://www.cnblogs.com/Blueses/p/5562393.html