這篇文章給大家介紹Java中怎么啟動和終止線程,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
在Java中我們啟動線程都是調用Thread類中的start()方法來啟動,當線程處理完run()方法里面的邏輯后自動終止。但是在調用start()方法之前,我們需要先構建一個Thread對象,一般我們都是直接使用Thread類的構造函數來創建一個線程對象,Thread構造函數定義如下:
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類中的定義如下:
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異常。說完了線程的啟動,我們在來說說線程的終止。
我們在看Thread類的源碼的時候,發現Thread類提供了stop()、suspend()和resume()方法來講線程終止,暫停和恢復。但是這些方法在Thread類中被標記為廢棄的方法,不推薦開發者使用這些方法。至于原因,小伙伴自己去查閱資料,這里LZ就不在贅述了。既然官方不推薦是用這么方法來終止線程,那我們應該應該用什么來代替呢? stop()方法的替代方案是在線程對象的run方法中循環監視一個變量,這樣我們就可以很優雅的終止線程。
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類上面的,因此任何類都能實現等待/通知。等待/通知方法定義如下:
// 通知一個在對象上等待的線程,使其從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線程才能獲取到鎖再次執行。
關于Java中怎么啟動和終止線程就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。