Java 多線程(程序終止)
💛線程的幾個狀态

💛線程終止
想要終止一個線程的時候, 不推薦使用使用java裡面的stop(), destory()以及一些過期的方法, 我們可以使用标志變量來控制讓線程自行終止, 這相對來說是比較安全的一種方式.
package com.smile.test.thread;
public class StopThread implements Runnable {
private boolean flag = true;
public static void main(String[] args) {
StopThread stopThread = new StopThread();
new Thread(stopThread, "test").start();
for (int i = 0; i < 1000; i++) {
if (i == 999){
stopThread.stop();
}
System.out.println(Thread.currentThread().getName() + i);
}
}
@Override
public void run() {
while (flag){
System.out.println(Thread.currentThread().getName() + " is running");
}
}
private void stop(){
this.flag = false;
}
}