Thread的join方法

Thread类中的join方法的语义:

void java.lang.Thread.join() throws InterruptedException
Waits for this thread to die.

Throws:
InterruptedException if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

翻译为中文:等待这个线程死亡
即:在a线程中,调用b线程的join方法,a线程会同步直到b线程结束。
即(表达形式可能不太科学):

public void a(){
b.join();
// 继续执行需要b线程的run方法完成或者被中断
}


案例:

想要取一个二维数组中最大的值:可以让每个线程执行其中一个一维数组,并确定最大值,当所有的线程执行完成后再确定最终的最大值。

代码:

package com.horizon.thread.join;

/**
* 创建10个线程去计算最大值,然后取其中结果的最大值
*/
public class TenThreads {

private static class WorkerThread extends Thread {
int max = Integer.MIN_VALUE;
int[] ourArray;

public WorkerThread(int[] ourArray) {
this.ourArray = ourArray;
}

// Find the maximum value in our particular piece of the array
public void run() {
for (int i = 0; i < ourArray.length; i++)
max = Math.max(max, ourArray[i]);
}

public int getMax() {
return max;
}
}

public static int[][] getBigHairyMatrix() {
int[][] result=new int[10][10];
for(int i=0;i<result.length;i++){
for(int j=0;j<result[i].length;j++){
result[i][j]=i*j;
}
}
return result;
}

public static void main(String[] args) {
WorkerThread[] threads = new WorkerThread[10];
int[][] bigMatrix = getBigHairyMatrix();
int max = Integer.MIN_VALUE;
// 给每个线程一个数组去计算
for (int i = 0; i < 10; i++) {
threads[i] = new WorkerThread(bigMatrix[i]);
threads[i].start();
}
// 等待每个线程结束,然后求取最大值
try {
for (int i = 0; i < 10; i++) {
//如果thread[i]没有执行完毕,那么不会继续向下执行,一直等待线程执行完毕!
threads[i].join(); //此join方法会等待直到thread[i] 结束,即使是thread[i+1]已经完成,main方法也不会向下执行。如果thraed[i].join()没有返回,thread[i+1] 的join方法也不会调用
System.out.println(i+"---"+threads[i].getMax());
max = Math.max(max, threads[i].getMax());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Maximum value was " + max);
}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值