~~~
package cn.com.Comthread.ThreadDemo6;
public class ClimbThread implements Runnable {
private int time;
private int num; //100米
public ClimbThread(int time, int num) {
this.time = time;
this.num = num;
}
public double getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
@Override
public void run() {
if (Thread.currentThread().getName().equals("年轻人")) {
for (int i = 1; i <= 10; i++) {
try {
Thread.sleep(1000*this.time);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "爬完" + num + "米");
}
System.out.println("年轻人到达终点!");
}else{
for (int i = 1; i <= 10; i++) {
try {
Thread.sleep(1000*this.time);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "爬完" + num + "米");
}
System.out.println("老年人到达终点!");
}
}
}
~~~
Test测试类:
~~~
package cn.com.Comthread.ThreadDemo6;
public class Test {
public static void main(String[] args) {
Thread t1 = new Thread(new ClimbThread(5,100),"年轻人");
Thread t2 = new Thread(new ClimbThread(10,100),"老年人");
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
}
}
~~~
while循环实现:
~~~
package comthread;
public class ClimbThread extends Thread {
private int time; // 爬100米的时间
public int num = 0; // 爬多少个100米
public ClimbThread(String name, int time, int kilometer) {
super(name);
this.time = time;
this.num = kilometer * 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()+"到达终点!");
}
public static void main(String[] args) {
ClimbThread youngMan = new ClimbThread("年轻人",500,1);
ClimbThread oldMan = new ClimbThread("老年人",1500,1);
System.out.println("********开始爬山*********");
youngMan.start();
oldMan.start();
}
}
~~~