如何停止一个进程

https://cloud.tencent.com/developer/article/1451817

  1. 使用退出标志,使线程正常退出,也就是当run方法完成后线程终止。
  2. 使用interrupt方法中断线程。
  3. 不推荐使用 stop、suspend及resume 方法。相当于电脑断电关机一样,是不安全的方法。

使用退出标志

线程当中一般都会写循环,如果不写循环,一句话能搞定的事,就没必要再开线程来处理。 stop方法已经过时, run方法结束。 开启多线程时,运行代码通常是循环结构,只要控制住循环,就可以让run方法结束,也就是线程结束。 原理:只要循环终止了,线程也就终止了。

public class StopThread implements Runnable{ private volatile boolean flag = true; @Override public void run() { while (flag) { System.out.println(Thread.currentThread().getName() + "...run"); } System.out.println("...stop"); } public void set() { flag = false; } }

使用了一个关键字 volatile,保证当前 flag 在多核CPU 下的可见性。

package com.liukai.thread.stop;

public class MyThread extends Thread { public void run(){ super.run(); try { for(int i=0; i<5000; i++){ if (i == 100) { System.out.println("主动中断线程"); Thread.currentThread().interrupt(); } System.out.println("i="+(i+1)); Thread.sleep(100); } } catch (InterruptedException e) { e.printStackTrace(); } } }

猜你喜欢

转载自www.cnblogs.com/JMrLi/p/11593571.html