Java Thread

1 Tread join 方法
import java.util.Random;
/**
 * thread.join()应该是让当前线程block住,等thread执行完之后,再继续执行
 * 。比如有3个线程在执行计算任务,必须等三个线程都执行完才能汇总,那么这时候在主线程里面让三个线程join,最后计算结果既可。代码显示如下。
 * @author poy 2010-9-12 11:12:29
 */
public class ThreadJoinTest {
	public static void main(String[] args) {
		System.out.println("in " + Thread.currentThread().getName());
		long start = System.currentTimeMillis();
		CounterThread[] t = new CounterThread[3];
		for (int i = 0; i < t.length; i++) {
			t[i] = new CounterThread();
			t[i].start();
			try {
                t[i].join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
		}
		long end = System.currentTimeMillis();
		System.out.println("join total time = " + (end - start));
		int result = 0;
		for (int j = 0; j < t.length; j++) {
			result += t[j].getResult();
		}
		System.out.println("the result is " + result);
	}
}
class CounterThread extends Thread {
	
	private int result;
	
	public int getResult() {
		return result;
	}
	public void run() {
		try {
			int time = (new Random().nextInt() >>> 1) % 5000;
			Thread.sleep(time);
			System.out.println(Thread.currentThread().getName()
					+ " is blocked for " + time + "ms");
		} catch (InterruptedException ex) {
		}
		result = 5;
	}
}

运行结果:
in main
Thread-0 is blocked for 4255ms
Thread-1 is blocked for 4555ms
Thread-2 is blocked for 630ms
join total time = 9468
the result is 15

把 join方法注释掉,可以
//			try {
//                t[i].join();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }

运行结果:
in main
join total time = 0
the result is 0
Thread-2 is blocked for 1579ms
Thread-1 is blocked for 1944ms
Thread-0 is blocked for 4215ms

你可能感兴趣的:(java,thread,J#)