方法一:继承Thread类
public class AnimalAthletes extends Thread {
private long speed;
public AnimalAthletes(long speed) {
super();
this.speed = speed;
}
public void run(){ //覆盖Thread类的run()方法
System.out.println(currentThread().getName()+":起跑");
for (int i = 0; i < 10; i++) {
System.out.println(currentThread().getName()+" :"+i+"米 ");
try {
sleep(speed);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(currentThread().getName()+":到达终点");
}
}
public class RaceDemo {
public static void main(String[] args) {
AnimalAthletes tortoise = new AnimalAthletes(250);
AnimalAthletes rabbit = new AnimalAthletes(100);
AnimalAthletes snail = new AnimalAthletes(1000);
tortoise.setName("乌龟");
rabbit.setName("兔子");
snail.setName("蜗牛");
tortoise.start();
rabbit.start();
snail.start();
}
}
方法二:实现Runnable接口,作为线程任务存在
网友评论