EP33-性能優(yōu)化最佳實(shí)踐之多線程操作(2)

Thread.join方法

我們知道線程是搶占運(yùn)行時(shí)的,比如同時(shí)執(zhí)行兩個(gè)線程(也不能完全同時(shí),比如一個(gè)在前一行,一個(gè)在后一行),都執(zhí)行一個(gè)for循環(huán)迭代100次,打印當(dāng)前線程號(hào),你會(huì)發(fā)現(xiàn)每次執(zhí)行的結(jié)果都不一樣,兩個(gè)線程的線程號(hào)互相穿插著打印出來了,每次穿插的順序都不同。

Threadjoin方法就可以把交替執(zhí)行的線程合并成順序執(zhí)行,比如在B中調(diào)用了A,A join進(jìn)來了,那么就要等待A執(zhí)行一段時(shí)間,才繼續(xù)執(zhí)行B。注意,調(diào)用join的必須是線程A,不能是線程B,因?yàn)锽跟自己是同一個(gè)線程嘛。。然后參數(shù)mills代表B等待A執(zhí)行的duration,如果設(shè)置成0,就直到A執(zhí)行完了才執(zhí)行B。

join的主要實(shí)現(xiàn)是通過lock.wait,當(dāng)B線程調(diào)用A的 join,B會(huì)拿到A的鎖。
wait方法是native方法了,wait跟sleep有點(diǎn)像,sleep阻塞當(dāng)前線程,不釋放鎖。wait釋放鎖。用notify喚醒。

    /**
     * Waits at most {@code millis} milliseconds for this thread to
     * die. A timeout of {@code 0} means to wait forever.
     * 在這個(gè)線程死之前,最多等待mills長度的時(shí)間
     * This implementation uses a loop of {@code this.wait} calls
     * conditioned on {@code this.isAlive}. As a thread terminates the
     * {@code this.notifyAll} method is invoked. It is recommended that
     * applications not use {@code wait}, {@code notify}, or
     * {@code notifyAll} on {@code Thread} instances.
     */
    public final void join(long millis) throws InterruptedException {
        synchronized(lock) {
        long base = System.currentTimeMillis();
        long now = 0;

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

        if (millis == 0) {
            while (isAlive()) {
            //一直等待的這個(gè)線程執(zhí)行完
                lock.wait(0);
            }
        } else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                //等待delay時(shí)間
                lock.wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
        }
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容