zoukankan      html  css  js  c++  java
  • 多线程吃饺子练习

    创建一个带有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();
    }
    }

  • 相关阅读:
    Educational Codeforces Round 80 (Rated for Div. 2)
    2020 CCPC Wannafly Winter Camp
    Codeforces Round #613 (Div. 2)
    Codeforces Round #612 (Div. 2)
    Hello 2020
    Good Bye 2019
    Codeforces Round #590 (Div. 3)
    依赖注入
    Spring 拦截器
    rsync服务端一键安装rsync脚本(非源码)
  • 原文地址:https://www.cnblogs.com/whj1986556646/p/5559234.html
Copyright © 2011-2022 走看看