線程停止
(1)建議線程正常停止;利用次數,不建議死循環
(2)建議使用標志位;設置一個標志位
(3)不建議使用stop或者destroy等過時或者JDK不建議使用的方法
public class TestThread1 implements Runnable { //1.設置一個標識位 private boolean flag=true; @Override // 重寫方法 public void run() { int i=0; while (flag){ i++; System.out.println("run-----thread"+i); } } // 2 設置線程停止方法,改變停止條件 public void stop() { this.flag=false; } public static void main(String[] args) { //啟動線程 TestThread1 th=new TestThread1(); new Thread(th).start(); for (int i = 0; i < 1000; i++) { System.out.println("main=====>"+i); if(i==900){ // 調用stop 方法讓線程停止 th.stop(); System.out.println("該線程停止了"); } } } }
注意:推薦讓線程自己停止下來,不推薦使用JDK提供的stop(),destroy()等方法;
浙公網安備 33010602011771號