模拟多人徒步爬山,使用多线程模拟多人徒步爬山训练要点,使用任意一种方式创建线程,使用 Thread.sleep()方法设置线程休眠。需求说明:每个线程代表一个人可设置每人爬山速度每爬完 100 米显示信息爬到终点时给出相应提示。
代码:
MyRunnablethree.java
package duo2;
public class MyRunnablethree extends Thread{
private int time; public int num=0;
public MyRunnablethree(String name, int time,int kio) {
super(name); this.time = time; this.num=kio*1000/100;
}
@Override public void run() {
while (num>0){ try {
Thread.sleep(this.time);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"爬完 100 米!");
num--;
}
System.out.println(Thread.currentThread().getName()+"到达终点!");
}
}
Test1.java
package duo2;
public class Test1 {
public static void main(String[] args) {
MyRunnablethree aged=new MyRunnablethree("老年人",1500,1);
MyRunnablethree youngPeopl=new MyRunnablethree("年轻人",500,1);
System.out.println("********开始爬山********");
aged.start(); youngPeopl.start();
}
}
网友评论