标签:
创建一个带有run方法继承Tread的类
public class Race {
public class Child extends Thread{
private String name;
private long time;
private Plate p;
public Child(String name,Plate p,long time){
this.name = name;
this.p = p;
this.time = time;
}
@Override
public void run() {
// TODO Auto-generated method stub
int num = 0;
while(true){
synchronized (this.p){
if(this.p.getJz()==0){
break;
}
num++;
this.p.setJiaozi(this.p.getJz()-1);
System.out.println(this.name + "吃了第" + num + "个饺子!");
}
try {
Thread.sleep(time);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
再创建一个可以传参的方法
public class Plate {
private int jz = 25;
public int getJz() {
return jz;
}
public void setJiaozi(int jz) {
this.jz = jz;
}
}
创建main方法运行线程
public class EatJiaoZi {
public static void main(String[]args) {
Plate p = new Plate();
Child c1 =new Child("z",p,2000);
Child c2 =new Child("l",p,1500);
c1.start();
c2.start();
}
}
标签:
原文地址:http://www.cnblogs.com/whj1986556646/p/5559234.html