本文主要是介绍如何停掉一个线程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
public class TestDemo extends Thread{@Overridepublic void run() {//要执行的代码while(true){}}public static void main(String[] args) {new TestDemo().start();System.out.println(Thread.currentThread().getName()+"主线程已经运行完毕。。。");}
}
上面这个程序,我们来运行一下:
我们如何优雅的关闭了:定义一个标记
public class TestDemo extends Thread{//定义一个标记private static Boolean flag = true;@Overridepublic void run() {//要执行的代码while(flag){}}public static void main(String[] args) {new TestDemo().start();try{Thread.sleep(3000);}catch (Exception e){}flag = false;System.out.println(Thread.currentThread().getName()+"主线程已经运行完毕。。。");}
}
这篇关于如何停掉一个线程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!