另一种就是你自己设置一个停止线程的标记 (推荐这种) 代码如下: package com.demo; //测试Thread的stop方法和自己编写一个停止标记来停止线程; public class StopThread implements Runnable{ //停止线程的标记值boolean; private boolean flag = true; public void stopThread(){ flag = false; } public void run(){ int i=0; while(flag){ i++; System.out.println(Thread.currentThread().getName()+":"+i); try{ Thread.sleep(1000); }catch(Exception e){ } System.out.println(Thread.currentThread().getName()+"==>"+i); } } public static void main(String args[]){ StopThread st = new StopThread(); Thread th = new Thread(st); Thread th1 = new Thread(st); th.start(); th1.start(); try{ Thread.sleep(5500); }catch(Exception e){ } /* 如果使用Thread.stop方法停止线程,不能保证这个线程是否完整的运行完成一次 run方法;但是如果使用停止的标记位,那么可以保正在真正停止之前完整的运行完 成一次run方法; */ th.stop(); st.stopThread(); } }
线程关闭
最新推荐文章于 2023-11-04 16:03:22 发布