Java并发:join与wait
Thread.join中使用Object.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; } } }
wait方法,jdk文档中的解释时:Causes the current thread to wait ,wait方法会让当前线程从runnable变成waitting的状态。怎么理解这句话呢?首先每个对象都可以作为一个锁,wait方法是根类Object的方法,每个对象都有其wait方法,在main方法中执行如下代码:
public class Program{ public static void main(String[] args) throws Exception{ MyThread myThread = new Thread(new Runnable(){ @Override public void run() { //this就是当前对象myThread,同步获取到myThread锁 synchronized (this) { this.notify();//唤醒在myThread锁上等待的单个线程。即main主线程从waitting变成runnable,main方法继续执行 } } }); myThread.setName("myThread"); myThread.start(); //同步获取到myThread锁 synchronized (myThread) { //使当前线程(main)从runnable进入waitting状态,等待其他某个线程调用myThread锁的 notify方法 myThread.wait(); } }
myThread对象就是一个锁,main方法synchronized (myThread)获取到锁,并执行该锁的wait方法,使main线程一直等待,当线程MyThread中获取同一个锁,并执行该锁的notify方法,使之前因该锁等待main方法可以继续执行。