Posted on 2009-06-02 20:11
啥都寫點 閱讀(328)
評論(0) 編輯 收藏 所屬分類:
J2SE
關鍵技術:
- JDK1.1以前使用Thread的stop方法停止線程,現在已經不推薦使用了,原因是它可能引起死鎖。
- 為線程設置一個布爾屬性,標志線程是否運行,在run方法中適當地檢測該標志位,只有當它的值為true時,才繼續往下執行。但需要停止線程時,只需設置標志位為false即可。
package book.thread;
/**
* 停止線程
*/
public class StopThread {
/** 線程對象 */
private ThreadA thread = new ThreadA();
/** 自定義線程類 */
class ThreadA extends Thread{
//用一個boolean值標記線程是否需要運行。
private boolean running = false;
//覆蓋了父類的start方法,
public void start(){
//將running置為ture,表示線程需要運行
this.running = true;
super.start();
}
public void run(){
System.out.println("ThreadA begin!");
int i=0;
try {
//如果running為真,說明線程還可以繼續運行
while (running){
System.out.println("ThreadA: " + i++);
//sleep方法將當前線程休眠。
Thread.sleep(200);
}
} catch (InterruptedException e) {
}
System.out.println("ThreadA end!");
}
public void setRunning(boolean running){
this.running = running;
}
}
/**
* 啟動ThreadA線程
*/
public void startThreadA(){
System.out.println("To start ThreadA!");
thread.start();
}
/**
* 停止ThreadA線程
*/
public void stopThreadA(){
System.out.println("To stop ThreadA!");
thread.setRunning(false);
}
public static void main(String[] args) {
StopThread test = new StopThread();
//啟動ThreadA線程
test.startThreadA();
//當前線程休眠一秒鐘
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//停止ThreadA線程
test.stopThreadA();
}
}
--
學海無涯