java多人爬山多线程_练习-模拟多人爬山

~~~

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();

}

}

~~~

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值