Java併發:join與wait

  Thread.join中使用Object.wait實現:java

  //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方法中執行以下代碼:ide

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方法能夠繼續執行。this

相關文章
相關標籤/搜索