轉:基礎知識:檢測執行緒是否結束的方法收藏

herosoft發表於2008-09-02

檢測執行緒是否結束的方法收藏

[@more@]

Package net.java2000.lang;


/**
* 檢測執行緒是否結束的方法。
*
* @author 趙學慶,Java世紀網(java2000.net)
*
*/
public class ThreadDetermingFinish {

public static void main(String[] args) {
// 建立並啟動執行緒
MyThreadToDeterming thread = new MyThreadToDeterming();
thread.start();

// 非阻塞的方式檢測執行緒是否完成
if (thread.isAlive()) {
System.out.println("執行緒在執行中");
} else {
System.out.println("執行緒已經結束");
}

// 用一段指定的時間,等待執行緒結束
long delayMillis = 1000;
try {
System.out.println("開始等待一段時間...");
thread.join(delayMillis);

if (thread.isAlive()) {
System.out.println("等待結束:執行緒在執行中");
} else {
System.out.println("等待結束:執行緒已經結束");
}
} catch (InterruptedException e) {
System.out.println("等待被中斷了");
}

// 等待執行緒結束
try {
System.out.println("開始等待直到結束...");
thread.join();
System.out.println("執行緒已經結束");
} catch (InterruptedException e) {
System.out.println("等待被中斷了");
}

}

}

class MyThreadToDeterming extends Thread {
public void run() {
int i = 20;
while (i-- > 0) {
// 我們故意讓這個執行緒休眠100毫秒
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.getClass().getName() + " is running...");
}
System.out.println(this.getClass().getName() + " is stopping...");
}
}
執行結果

執行緒在執行中
開始等待一段時間...
net.java2000.lang.MyThreadToDeterming is running...
net.java2000.lang.MyThreadToDeterming is running...
net.java2000.lang.MyThreadToDeterming is running...
net.java2000.lang.MyThreadToDeterming is running...
net.java2000.lang.MyThreadToDeterming is running...
net.java2000.lang.MyThreadToDeterming is running...
net.java2000.lang.MyThreadToDeterming is running...
net.java2000.lang.MyThreadToDeterming is running...
net.java2000.lang.MyThreadToDeterming is running...
等待結束:執行緒在執行中
開始等待直到結束...
net.java2000.lang.MyThreadToDeterming is running...
net.java2000.lang.MyThreadToDeterming is running...
net.java2000.lang.MyThreadToDeterming is running...
net.java2000.lang.MyThreadToDeterming is running...
net.java2000.lang.MyThreadToDeterming is running...
net.java2000.lang.MyThreadToDeterming is running...
net.java2000.lang.MyThreadToDeterming is running...
net.java2000.lang.MyThreadToDeterming is running...
net.java2000.lang.MyThreadToDeterming is running...
net.java2000.lang.MyThreadToDeterming is running...
net.java2000.lang.MyThreadToDeterming is running...
net.java2000.lang.MyThreadToDeterming is stopping...
執行緒已經結束

Trackback:http://blog.csdn.net/java2000_net/archive/2008/08/29/2849890.aspx

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/220284/viewspace-1009967/,如需轉載,請註明出處,否則將追究法律責任。

相關文章