java多线程join和wait

join作用是阻塞主线程一直到子线程运行完毕

package com.ydy.thread;

import java.util.concurrent.atomic.AtomicInteger;

class Add implements Runnable{

	private AtomicInteger count=new AtomicInteger(0);
	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i=0;i<100000000;i++) {
			count.incrementAndGet();
		}
		
	}
	public AtomicInteger getCount() {
		return count;
	}
	
	
}

public class JoinTest {
	public static void main(String[] args) throws Exception {
		Add add=new Add();
		Thread t1=new Thread(add);
		Thread t2=new Thread(add);
		t1.start();
		t2.start();
		t1.join();//阻塞main线程,一直到t1线程运行完毕
		System.out.println("t1.join()");
		t2.join();
		System.out.println("t2.join()");
		
		System.out.println("countAll"+add.getCount());
	}

}

join实现原理是基于wait机制,以下代码选自java.lang.Thread

 public final synchronized void join(long millis)
    throws InterruptedException {
        long base = System.currentTimeMillis();
        long now = 0;

        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (millis == 0) {
            while (isAlive()) {
                wait(0);
            }
        } else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }

 

转载于:https://my.oschina.net/u/2446173/blog/3003660

你可能感兴趣的:(java多线程join和wait)