`

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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics