JAVA中終止執行緒的方法有哪些

來源:文萃谷 2.06W

JAVA的多執行緒程式設計中,ad型別包含了一些列的方法start(), stop(), stop(Throwable) and suspend(), destroy() and resume()。下面是小編為大家帶來的JAVA中終止執行緒的方法,歡迎閱讀

JAVA中終止執行緒的方法有哪些
  JAVA中終止執行緒的方法

Java的多執行緒程式設計中,ad型別包含了一些列的方法start(), stop(), stop(Throwable) and suspend(), destroy() and resume()。通過這些方法,我們可以對執行緒進行方便的操作,但是這些方法中,只有start()方法得到了保留。

在Sun公司的一篇文章《Why are , end and me Deprecated? 》中詳細講解了捨棄這些方法的原因。

如果真的.需要終止一個執行緒,可以使用以下幾種方法:

1、讓執行緒的run()方法執行完,執行緒自然結束。(這種方法最好)

2、通過輪詢和共享標誌位的方法來結束執行緒,例如while(flag){},flag的初始值設為真,當需要結束時,將flag的值設為false。(這種方法也不很好,因為如果while(flag){}方法阻塞了,則flag會失效)

public class SomeThread implements Runnable {

private volatile boolean stop = false;

public void terminate() {

stop = ture;

}

public void run() {

while(stop) {

// ... some statements

}

}

}

如果執行緒因為執行sleep()或是wait()而進入Not Runnable狀態,假如是wait() 用標誌位就方法就不行了,

public final void wait(long timeout)

throws InterruptedException

此方法導致當前執行緒(稱之為 T)將其自身放置在物件的等待集中,然後放棄此物件上的所有同步要求。即當前執行緒變為等待狀態

  wait() 的標準使用方法

synchronized(obj){

while(<不滿足條件>){

();

}

滿足條件的處理過程

}

而您想要停止它,您可以使用第三種即

3 使用interrupt(),而程式會丟出InterruptedException例外,因而使得執行緒離開run()方法,

例如:

public class SomeThread {

public static void main(String[] args)

{

Thread thread=new Thread(new Runnable(){

public void run() {

while (!rrupted()) {

// 處理所要處理的工作

try {

tln("go to sleep");

p(1000);

} catch (InterruptedException e) {

tStackTrace();

tln("i am interrupted!");

}

});

t();

rrupt();

}

}

執行結果為:

go to sleep

i am interrupted!

熱門標籤