迫于需求,有时候我们需要在一个线程中写上一个死循环,那么问题来了:当线程启动开始运行时,我们如何有效的结束该死循环,这里给大家总结如下几种方式:
方式一:线程中循环条件为线程全局变量
文件1:
public class TestThread extends Thread{ boolean isStop = true; public void stopThread(){ isStop = false; } @Override public void run() { while(isStop){ System.out.println("线程正在运行..."); } System.err.println("线程已停止运行..."); } }
文件2:
public class Test { public static void main(String[] args) throws InterruptedException { TestThread thread = new TestThread(); thread.start(); Thread.sleep(2000); thread.stopThread(); } }
方式二:线程中循环条件使用isInterrupted方法
文件1:
public class TestThread extends Thread { public void run() { while (!Thread.currentThread().isInterrupted()) { System.out.println("线程正在运行..."); } System.err.println("线程已停止运行..."); } }
文件2:
public class Test{ public static void main(String args[]) throws Exception { TestThread thread = new TestThread(); thread.start(); Thread.sleep(1000); thread.interrupt();// 发出中断请求 } }
方式三:在循环体中写一行出现异常的代码(不可取)
文件1:
public class TestThread extends Thread { @Override public void run() { try { while (true) { System.out.println("线程正在运行..."); Thread.sleep(1000);//不能缺少 } } catch (InterruptedException e) { e.printStackTrace(); } System.err.println("线程已停止运行..."); } }
文件2:
public class Test { public static void main(String[] args) throws InterruptedException { TestThread thread = new TestThread(); thread.start(); Thread.sleep(2000); thread.interrupt(); } }