使用thread类

来源:互联网 发布:java实现推荐算法实例 编辑:程序博客网 时间:2024/06/05 20:48
package thread;public class Example_1 {public static void main(String args[]){Home home=new Home();Thread dog,cat;home.setFood(20);cat=new Thread(home);dog=new Thread(home);dog.setName("狗");cat.setName("猫");cat.start();dog.start();}}class Home implements Runnable{int foodAmount;public void setFood(int w){foodAmount=w;}public void run(){while(true){String name=Thread.currentThread().getName();if(name.equals("狗")){System.out.println(name+"吃饭");foodAmount-=2;}else if(name.equals("猫")){System.out.println(name+"吃饭");foodAmount-=1;}System.out.println(" 剩 "+foodAmount);try{Thread.sleep(2000);}catch(InterruptedException e){}if(foodAmount<=0)return ;}}}

0 0
原创粉丝点击