Java線程的啓動和終止

在Java中咱們啓動線程都是調用Thread類中的start()方法來啓動,當線程處理完run()方法裏面的邏輯後自動終止。可是在調用start()方法以前,咱們須要先構建一個Thread對象,通常咱們都是直接使用Thread類的構造函數來建立一個線程對象,Thread構造函數定義以下:java

public Thread() {
    init(null, null, "Thread-" + nextThreadNum(), 0);
}

public Thread(Runnable target) {
    init(null, target, "Thread-" + nextThreadNum(), 0);
}

Thread(Runnable target, AccessControlContext acc) {
    init(null, target, "Thread-" + nextThreadNum(), 0, acc, false);
}

public Thread(ThreadGroup group, Runnable target) {
    init(group, target, "Thread-" + nextThreadNum(), 0);
}

public Thread(String name) {
    init(null, null, name, 0);
}

public Thread(ThreadGroup group, String name) {
    init(group, null, name, 0);
}

public Thread(Runnable target, String name) {
    init(null, target, name, 0);
}

public Thread(ThreadGroup group, Runnable target, String name) {
    init(group, target, name, 0);
}

public Thread(ThreadGroup group, Runnable target, String name,
    long stackSize) {
    init(group, target, name, stackSize);
}

咱們能夠看到在Thread類中定義了這麼多的構造函數,可是這些構造函數都是調用init()方法來完成Thread對象的構建,init方法定義以下:安全

private void init(ThreadGroup g, Runnable target, String name,
    long stackSize) {
    init(g, target, name, stackSize, null, true);
}

/**
 * 
 * @param g  線程組
 * @param target   調用run方法的對象
 * @param name    建立新線程的名稱
 * @param stackSize   構建新線程所須要的堆棧大小   stackSize的值爲0時,表示忽略這個參數
 * @param acc          上下文
 * @param inheritThreadLocals  是否繼承thread-locals
 */
private void init(ThreadGroup g, Runnable target, String name,long stackSize, AccessControlContext acc,boolean inheritThreadLocals) {
    if (name == null) {
        throw new NullPointerException("name cannot be null");
    }

    this.name = name;
    //構建線程的父線程就是當前正在運行的線程
    Thread parent = currentThread();
    SecurityManager security = System.getSecurityManager();
    if (g == null) {
        
        if (security != null) {
            g = security.getThreadGroup();
        }

        //若是線程組爲空,則嘗試用父線程的線程組
        if (g == null) {
            g = parent.getThreadGroup();
        }
    }

    //安全檢查
    g.checkAccess();
    if (security != null) {
        if (isCCLOverridden(getClass())) {
            security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
        }
    }

    // 增長線程組中未啓動線程的數量
    g.addUnstarted();

    this.group = g;
    //繼承父線程的Daemon屬性
    this.daemon = parent.isDaemon();
    //繼承父線程的優先級
    this.priority = parent.getPriority();
    //構建合適的類加載器
    if (security == null || isCCLOverridden(parent.getClass()))
        this.contextClassLoader = parent.getContextClassLoader();
    else
        this.contextClassLoader = parent.contextClassLoader;
    this.inheritedAccessControlContext =
        acc != null ? acc : AccessController.getContext();
    this.target = target;
    setPriority(priority);
    if (inheritThreadLocals && parent.inheritableThreadLocals != null)
        this.inheritableThreadLocals =
        ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
    this.stackSize = stackSize;

    //給新線程分配一個ID
    tid = nextThreadID();
}

從init方法中咱們看到,線程daemon屬性、線程的優先級、資源加載的contextClassLoader以及可繼承的ThreadLocal都是繼承自父線程。從這裏也也驗證了前面文章中提到的線程優先級的繼承性。在init()方法執行完畢後,一個線程對象就被構建出來了,它存放在堆內存中等待調用start()方法啓動。start()方法在Thread類中的定義以下:ide

public synchronized void start() {
   // 構建線程threadStatus默認值爲0
    if (threadStatus != 0)
        throw new IllegalThreadStateException();
    /**
     * 通知線程組,該線程即將開始啓動,將該現場添加到線程組中
     */
    group.add(this);

    boolean started = false;
    try {
        start0();
        started = true;
    } finally {
        try {
            if (!started) {
                //啓動線程失敗,將該線程從線程組中移除
                group.threadStartFailed(this);
            }
        } catch (Throwable ignore) {
           
        }
    }
}

private native void start0();

void add(Thread t) {
    synchronized(this) {
        // 若是線程已經銷燬,則拋出異常
        if (destroyed) {
            throw new IllegalThreadStateException();
        }
        // 線程組爲空,初始化線程組
        if (threads == null) {
            threads = new Thread[4];
        } else if (nthreads == threads.length) {
            //線程組已經滿,則擴容,擴容的大小爲原來的2倍
            threads = Arrays.copyOf(threads, nthreads * 2);
        }
        // 將線程添加到線程組中
        threads[nthreads] = t;

        // 啓動線程數量加一
        nthreads++;

        //爲啓動的線程數量減一
        nUnstartedThreads--;
    }
}

void threadStartFailed(Thread t) {
    synchronized(this) {
        remove(t);
        nUnstartedThreads++;
    }
}

private void remove(Thread t) {
    synchronized(this) {
        if (destroyed) {
            return;
        }
        for (int i = 0; i < nthreads; i++) {
            if (threads[i] == t) {
                System.arraycopy(threads, i + 1, threads, i, --nthreads - i);
                threads[nthreads] = null;
                break;
            }
        }
    }
}

從上面源碼中,咱們能夠看出start()方法最終是調用本地方法start0()方法啓動線程的。那麼start0()這個本地方法具體作了那些事情呢,它主要完成了將Thread在虛擬機中啓動,執行構建Thread對象時重寫的run()方法,修改threadStatus的值。 從上面start()方法的源碼中,start()方法時不能被重複調用的,當重複調用start()方法時,會拋出IllegalThreadStateException異常。說完了線程的啓動,咱們在來講說線程的終止。函數

<font color="#EE30A7">線程終止</font>

咱們在看Thread類的源碼的時候,發現Thread類提供了stop()、suspend()和resume()方法來說線程終止,暫停和恢復。可是這些方法在Thread類中被標記爲廢棄的方法,不推薦開發者使用這些方法。至於緣由,小夥伴本身去查閱資料,這裏LZ就不在贅述了。既然官方不推薦是用這麼方法來終止線程,那咱們應該應該用什麼來代替呢? stop()方法的替代方案是在線程對象的run方法中循環監視一個變量,這樣咱們就能夠很優雅的終止線程。this

public class ThreadOne extends Thread {

    private volatile boolean flag = true;

    @Override
    public void run() {

        while (flag) {
            System.out.println(System.currentTimeMillis() / 1000 + " 線程正在運行");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }


    public static void main(String[] args) throws InterruptedException {

        ThreadOne t = new ThreadOne();
        t.start();
        TimeUnit.SECONDS.sleep(5);
        t.flag = false;

    }
}
output:
1554371306 線程正在運行
1554371307 線程正在運行
1554371308 線程正在運行
1554371309 線程正在運行
1554371310 線程正在運行

從上面的示例中,咱們能夠看到線程在運行了5秒中後,自動關閉了。這是由於主線程在睡眠了5秒後,給ThreadOne類中的flag值賦予了false值。線程

suspend()和resume()方法的替代方案是使用等待/通知機制。等待/通知的方法是定義在Object類上面的,所以任何類都能實現等待/通知。等待/通知方法定義以下:code

// 通知一個在對象上等待的線程,使其從wait()方法返回,而從wait()方法返回的前提是須要獲取鎖
public final native void notify();
// 通知全部對象上等待的線程,
public final native void notifyAll();
// 超時等待,線程在對象上等待timeout毫秒,若是時間超過則直接返回
public final native void wait(long timeout) throws InterruptedException;
// 超時等待,超時等待的時間能夠控制到納秒
public final void wait(long timeout, int nanos) throws InterruptedException
// 線程在對象上等待,直到有其它的線程調用了notify()或者notifyAll()方法
public final void wait() throws InterruptedException {
    wait(0);
}

等待/通知示例以下:對象

public class NotifyAndWait {

    public static void main(String[] args) {
        Object lock = new Object();
        WaitThread waitThread = new WaitThread(lock, "WaitThread");
        waitThread.start();

        NotifyThread notifyThread = new NotifyThread(lock, "NotifyThread");
        notifyThread.start();
    }
}

class WaitThread extends Thread {
    private Object lock;

    public WaitThread(Object lock, String name) {
        super(name);
        this.lock = lock;
    }
    @Override
    public void run() {
        synchronized(lock) {
            System.out.println(Thread.currentThread().getName() + "開始運行...");
            try {
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "執行完成...");
        }
    }
}

class NotifyThread extends Thread {
    private Object lock;

    public NotifyThread(Object lock, String name) {
        super(name);
        this.lock = lock;
    }
    @Override
    public void run() {
        synchronized(lock) {
            System.out.println(Thread.currentThread().getName() + "開始運行...");
            lock.notify();
            System.out.println(Thread.currentThread().getName() + "執行完成...");
        }
    }
}
output:
WaitThread開始運行...
NotifyThread開始運行...
NotifyThread執行完成...
WaitThread執行完成...

從上面的示例代碼中咱們看到,當WaitThread線程調用start()方法後,當指定了wait()方法將釋放作進入到等待隊列,而後NotifyThread獲取到了鎖,當通知線程執行了notify()方法後,將會通知等待在該鎖上面的線程,當NotifyThread線程運行完成後,WaitThread線程將會從新回覆執行。 調用wait()方法和notify()方法須要注意一下幾點:繼承

  • 調用wait()或notify()方法以前須要獲取到鎖。
  • 當調用wait()方法後,線程會已經釋放鎖。
  • 當調用wait()方法後,線程將從運行狀態轉變爲WAITING狀態,並將線程方法到等待隊列中。
  • 當調用notify()/notifyAll()方法後,線程不會當即釋放鎖,它必須在線程執行完後釋放鎖,wait線程才能獲取到鎖再次執行。
相關文章
相關標籤/搜索