Java中一般使用两种方法来使线程终止的方法,一是标志位的方法,二是中断使用标志位代码实现如下。
// 线程停止的方式:1加标志位;2 中断 class Stop implements Runnable { private boolean flag = true; @Override public void run() { while (flag) { for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName() + "=====" + i); } } } public void setFlag(boolean flag) { this.flag = flag; } } public class ThreadStop { public static void main(String[] args) { Stop stop = new Stop(); Thread bobi = new Thread(stop, "Bobi"); bobi.start(); for (int i = 0; i < 10; i++) { System.out.println( "i=" + i); // 通过标志位让线程停下来 if (i >= 9) { stop.setFlag(false); } System.out.println(Thread.currentThread().getName() + "=====" + i); } System.out.println(Thread.currentThread().getName() + "=====over======"); } }使用中断实现线程停止的代码实现如下。
// 线程停止的方式:1加标志位;2 中断 class Stop implements Runnable { private boolean flag = true; @Override public void run() { while (flag) { // 若此时不在main方法中对中断方法做处理的话,线程是停不下来的(虽然main线程停了)。 synchronized (this) { try { wait(); } catch (InterruptedException e) { //e.printStackTrace(); // 强制获取cpu之后会进入这里改变flag的值 flag = false; } } for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName() + "=====" + i); } } } public void setFlag(boolean flag) { this.flag = flag; } } public class ThreadStop { public static void main(String[] args) { Stop stop = new Stop(); Thread bobi = new Thread(stop, "Bobi"); bobi.start(); for (int i = 0; i < 10; i++) { // 通过标志位让线程停下来 if (i >= 9) { // 强制让bobi这个线程获取cpu,执行完没有完成的操作,而不是一直处于等待状态。 bobi.interrupt(); } System.out.println(Thread.currentThread().getName() + "=====" + i); } System.out.println(Thread.currentThread().getName() + "=====over======"); } }