Java 多线程怎么停止线程?
本示例将调用interrupt()方法来停止线程,但是interrupt()方法的使用效果并不像 for+break 语句那样,马上就停止循环。调用interrupt()方法仅仅是在当前线程中打了一个停止标记,并不是真的停止线程。
拓展,先来了解两个方法
1.interrupted()测试当前线程是否已经中断
package test; import exthread.MyThread; import exthread.MyThread; public class Run2 { public static void main(String[] args) { Thread.currentThread().interrupt(); System.out.println("是否停止1?=" + Thread.interrupted()); System.out.println("是否停止2?=" + Thread.interrupted()); System.out.println("end!"); } }
运行结果:
是否停止1?=true
是否停止2?=false
end!
jdk中说明:如果程序两次调用interrupted()方法的话。第二次的结果为false;
扫描二维码关注公众号,回复:
1112781 查看本文章
2.isinterrupted()
package test; import exthread.MyThread; import exthread.MyThread; public class Run3 { public static void main(String[] args) { try { MyThread thread = new MyThread(); thread.start(); Thread.sleep(100); thread.interrupt(); System.out.println("是否停止1?="+thread.isInterrupted()); System.out.println("是否停止2?="+thread.isInterrupted()); } catch (InterruptedException e) { System.out.println("main catch"); e.printStackTrace(); } System.out.println("end!"); } }
运行结果:
是否停止1?=true
是否停止2?=true
两种方法的区别:
1.检查当前线程是否打上了中断标记 执行两次第二次的时候清除标记
2.第二个方法检查线程Thread对象是否打上了中断标记 执行两次不清除标记