android等待多个线程结束,给定三个线程如何顺序执行完以后在主线程拿到执行结果...

-欢迎关注我的公众号:

![我的公众号](https://markdown-1258186581.cos.ap-shanghai.myqcloud.com/20190606104746.png)

# 给定三个线程如何顺序执行完以后在主线程拿到执行结果

这里采用线程的 join 方法实现,在一个线程 A 内部如果调用另外一个线程 B 的 join 方法,那么线程 A 就会等待 B 执行完以后再执行。

定义线程 Thread11:

```java

class Thread11 implements Runnable {

private String name;

private Thread thread;

public Thread11(String name) {

this.name = name;

}

public Thread getThread() {

return thread;

}

public void setThread(Thread thread) {

this.thread = thread;

}

@Override

public void run() {

System.out.println(name+ "线程运行开始!");

try {

if (thread!=null)

thread.join();

Thread.sleep(2000);

} catch (InterruptedException e) {

e.printStackTrace();

} finally {

System.out.println(name + "线程运行结束!");

}

}

}

```

创建三个线程:

```java

Thread11 thread1 = new Thread11("线程A");

Thread11 thread2 = new Thread11("线程B");

Thread11 thread3 = new Thread11("线程C");

Thread threadA = new Thread(thread1);

Thread threadB = new Thread(thread2);

Thread threadC = new Thread(thread3);

```

这里创建A、B、C三个线程,下面的操作是让线程按照 A -> B -> C -> 主线程的顺序执行:

```java

public static void main(String[] args) {

System.out.println(Thread.currentThread().getName() + "线程运行开始!");

Thread11 thread1 = new Thread11("线程A");

Thread11 thread2 = new Thread11("线程B");

Thread11 thread3 = new Thread11("线程C");

Thread threadA = new Thread(thread1);

Thread threadB = new Thread(thread2);

Thread threadC = new Thread(thread3);

thread2.setThread(threadA);

thread3.setThread(threadB);

threadA.start();

threadB.start();

threadC.start();

try {

threadC.join();

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println(Thread.currentThread().getName() + "线程运行结束!");

}

```

运行结果:

![](https://markdown-1258186581.cos.ap-shanghai.myqcloud.com/20200229002657.png)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值