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

多线程吃饺子练习

时间:2016-06-04 19:32:00      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:

创建一个带有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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!