第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

java多線程 關(guān)于join 的問題

java多線程 關(guān)于join 的問題

呼啦一陣風(fēng) 2019-02-19 16:05:09
我想通過join讓線程 a b c d順序打印,但是現(xiàn)在是亂序打印 public class ExJoin extends Thread { Thread thread; public ExJoin(){ } public ExJoin(Thread thread){ this.thread = thread; } @Override public void run() { try { if (thread != null){ thread.join(); } System.out.println(Thread.currentThread().getName()+" is running"); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { Thread threadA = new ExJoin(); threadA.setName("A"); Thread threadB = new ExJoin(threadA); threadB.setName("B"); Thread threadC = new ExJoin(threadB); threadC.setName("C"); Thread threadD = new ExJoin(threadC); threadD.setName("D"); threadC.start(); threadD.start(); threadA.start(); threadB.start(); } }
查看完整描述

3 回答

?
HUX布斯

TA貢獻1876條經(jīng)驗 獲得超6個贊

按照樓主的代碼邏輯,join是無法做到有序的,因為A/B/C/D線程的啟動運行依賴于CPU調(diào)度,如果線程B未啟動線程C調(diào)用threadB.join方法是不會生效的??梢钥纯?code>jdk內(nèi)置的邏輯實現(xiàn)isAlive()false時直接返回了。

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;
        }
    }
}
查看完整回答
反對 回復(fù) 2019-03-01
?
慕蓋茨4494581

TA貢獻1850條經(jīng)驗 獲得超11個贊

run方法中sleep(1000)確實會順序出現(xiàn)。我猜測可能是指令重排序,前面的線程已經(jīng)就緒,但是后面的線程對象還沒有創(chuàng)建出來,所以出現(xiàn)了亂序。

查看完整回答
反對 回復(fù) 2019-03-01
  • 3 回答
  • 0 關(guān)注
  • 486 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號