本文實例講述了Java通過在主循環中判斷Boolean來停止線程的方法。分享給大家供大家參考,具體如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
package Threads; /** * Created by Frank */ public class StopBoolean extends Thread { // 確保變化對其它線程可見(主要是主線程要可見) protected volatile boolean done = false ; public void run() { while (!done) { System.out.println( "StopBoolean running" ); try { sleep( 720 ); } catch (InterruptedException e) { return ; } } System.out.println( "StopBoolean finished" ); } public void shutDown() { done = true ; } public static void main(String[] args) throws InterruptedException { StopBoolean t1 = new StopBoolean(); t1.start(); Thread.sleep( 1000 * 5 ); t1.shutDown(); } } |
希望本文所述對大家java程序設計有所幫助。