Thread.stop, Thread.suspend, Thread.resume 和Runtime.runFinalizersOnExit 這些終止線程運(yùn)行的方法已經(jīng)被廢棄,使用它們是極端不安全的!
1.線程正常執(zhí)行完畢,正常結(jié)束
也就是讓run方法執(zhí)行完畢,該線程就會正常結(jié)束。
但有時候線程是永遠(yuǎn)無法結(jié)束的,比如while(true)。
2.監(jiān)視某些條件,結(jié)束線程的不間斷運(yùn)行
需要while()循環(huán)在某以特定條件下退出,最直接的辦法就是設(shè)一個boolean標(biāo)志,并通過設(shè)置這個標(biāo)志來控制循環(huán)是否退出。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public class ThreadFlag extends Thread { public volatile boolean exit = false ; public void run() { while (!exit) { System.out.println( "running!" ); } } public static void main(String[] args) throws Exception { ThreadFlag thread = new ThreadFlag(); thread.start(); sleep( 1147 ); // 主線程延遲5秒 thread.exit = true ; // 終止線程thread thread.join(); System.out.println( "線程退出!" ); } } |
3.使用interrupt方法終止線程
如果線程是阻塞的,則不能使用方法2來終止線程。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public class ThreadInterrupt extends Thread { public void run() { try { sleep( 50000 ); // 延遲50秒 } catch (InterruptedException e) { System.out.println(e.getMessage()); } } public static void main(String[] args) throws Exception { Thread thread = new ThreadInterrupt(); thread.start(); System.out.println( "在50秒之內(nèi)按任意鍵中斷線程!" ); System.in.read(); thread.interrupt(); thread.join(); System.out.println( "線程已經(jīng)退出!" ); } } |
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。