java 多线程 函数_java-多线程-join函数

packagecom.wp.join;public classJoinTest2 {private static int num = 0;static class JoinThreadA extendsThread {

@Overridepublic voidrun() {while (true) {

num++;long now =System.currentTimeMillis();while (System.currentTimeMillis() - now < 200) {

}

System.out.println("选手A已跑" + num + "米");if (num >= 100) {break;

}

}

}

}static class JoinThreadB extendsThread {protectedJoinThreadA joina;publicJoinThreadB(JoinThreadA joina) {this.joina =joina;

}

@Overridepublic voidrun() {try{

joina.join();

}catch(InterruptedException e) {

e.printStackTrace();

}while (true) {

num++;long now =System.currentTimeMillis();while (System.currentTimeMillis() - now < 100) {

}

System.out.println("选手B已跑" + num + "米");if (num >= 200) {break;

}

}

}

}static class JoinThreadC extendsThread {protectedJoinThreadB joinb;publicJoinThreadC(JoinThreadB joinb) {this.joinb =joinb;

}

@Overridepublic voidrun() {try{

joinb.join();

}catch(InterruptedException e) {

e.printStackTrace();

}while (true) {

num++;long now =System.currentTimeMillis();while (System.currentTimeMillis() - now < 50) {

}

System.out.println("选手C已跑" + num + "米");if (num >= 300) {break;

}

}

}

}static class JoinThreadD extendsThread {protectedJoinThreadC joinc;publicJoinThreadD(JoinThreadC joinc) {this.joinc =joinc;

}

@Overridepublic voidrun() {try{

joinc.join();

}catch(InterruptedException e) {

e.printStackTrace();

}while (true) {

num++;long now =System.currentTimeMillis();while (System.currentTimeMillis() - now < 20) {

}

System.out.println("选手D已跑" + num + "米");if (num >= 400) {break;

}

}

}

}public static void main(String[] args) throwsException {

System.out.println("比赛开始");

JoinThreadA joina= newJoinThreadA();

JoinThreadB joinb= newJoinThreadB(joina);

JoinThreadC joinc= newJoinThreadC(joinb);

JoinThreadD joind= newJoinThreadD(joinc);

joina.start();

joinb.start();

joinc.start();

joind.start();

joind.join();

System.out.println("比赛结束,最终跑完" + num + "米");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值