Thread基本功能解析

hwh405發表於2024-12-08

start

// 同步方法
 public synchronized void start() {
// 檢查執行緒狀態
        if (threadStatus != 0)
            throw new IllegalThreadStateException();

//新增到指定執行緒組,thread預設使用呼叫執行緒的執行緒組
        group.add(this);
        boolean started = false;
        try {
//本地方法啟動執行緒
            start0();
            started = true;
        } finally {
            try {
                if (!started) {
//開啟失敗則由執行緒組處理,從組內移除,並進行計數
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
                /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
            }
        }
    }

join

//所有join方法的過載最終都會進入此方法,入參為0時代表永久等待,原始語義為等待本執行緒死亡直到x秒
//isAlive方法由檢視eetop值判斷
public final synchronized void join(final long millis)
    throws InterruptedException {
//有時間限制
        if (millis > 0) {
            if (isAlive()) {
                final long startTime = System.nanoTime();
                long delay = millis;
                do {
//直接使用wait方法
                    wait(delay);
                } while (isAlive() && (delay = millis -
                        TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)) > 0);
            }
        } else if (millis == 0) {
            while (isAlive()) {
                wait(0);
            }
        } else {
            throw new IllegalArgumentException("timeout value is negative");
        }
    }

相關文章