用到的知识点:
1、定时时器的简单使用与停止
2、与oc的区别 ,可以再定义类的成员变量的时候给初始值
1 /* 2 首先创建一个文件:a.java 3 需求: 使用java描述一个车与修车厂两个事物, 车具备的公共属性:轮子数、 名字、 颜色 ,还 4 具备跑的功能行为。跑之前要检测轮子是否少于了4个,如果少于了4个,那么要送到修车厂修理, 5 修车厂修理之后,车的轮子数要补回来4个。 然后车就继续的跑起来。 6 7 修车厂: 具备公共属性: 名字、 地址、 电话。 8 公共的行为: 修车。 9 */10 import java.util.*;11 class Car //类名要大写12 {13 //int wheel =4;14 int wheel; //轮子15 String name; //名字 16 String color; //颜色17 String run; //跑18 public void run(){19 System.out.println("轮子齐了,可以开车了");20 }21 public void notRun(){22 System.out.println("轮子没齐,正在修理,不可以开");23 }24 }25 class Repair //修理26 {27 public void repair(Car car){28 car.wheel=4;29 }30 }31 32 class a33 {34 public static void main(String[] args){35 //定时器的使用36 Timer timer = new Timer(); 37 timer.schedule(new TimerTask() { 38 public void run() { //这个方法是系统的,必须要写不然就报错了39 Car car = new Car();40 car.wheel=(int)Math.random()*4+1;41 while(car.wheel!=4){42 car.notRun();43 Repair repair=new Repair();44 //给一个延时修理的时间-----开始45 Timer timer = new Timer();46 timer.schedule(new TimerTask(){47 public void run(){48 Repair repair=new Repair();49 repair.repair(car); //维修车50 timer.cancel(); //停止定时器51 }52 },1000);53 // 结束54 }55 car.run();56 timer.cancel(); //停止定时器57 } 58 }, 2000);// 设定指定的时间time,此处为2000毫秒 59 }60 }