1.使用Thread.stop()?
极力不推荐此方式,此函数不安全且已废弃,具体可参考Java API文档
2.设置终止标识,例如:
import static java.lang.System.out;public class TestThread extends Thread{ private boolean terminationFlag; public void run() { for (int i = 0; i != 10000000; ++i) { if (terminationFlag) break; out.println(i + 1); } } public void terminate() { terminationFlag = true; }}
3.使用Thread.interrupt()
interrupt()函数本身并不能终止线程,需要做一些处理方可终止线程
①若线程任务中包含Object.wait()、Thread.sleep(long)等可能引发InterruptedException的函数,则在调用interrupt()后会抛出InterruptedException
import static java.lang.System.out;import java.util.logging.Logger;import java.util.logging.Level;public class TestThread extends Thread{ private static final Logger LOGGER = Logger.getLogger("TestThread"); public void run() { for (int i = 0; i != 10000000; ++i) { try { Thread.sleep(100); out.println(i + 1); } catch (InterruptedException ex) { LOGGER.log(Level.SEVERE, null, ex); break; //执行break后退出循环,run()也将执行完毕 } } }}
②若线程任务中不包含可能引发InterruptedException的函数,则可将Thread.isInterrupted()的返回值作为终止标识
import static java.lang.System.out;public class TestThread extends Thread{ public void run() { for (int i = 0; i != 10000000; ++i) { if (isInterrupted()) break; out.println(i + 1); } out.println("TestThread.run() will be finished"); }}