如何结束线程-线程中断
manongba · 490浏览 · 发布于2019-09-16
停止现成的方式
线程停止的方式:
线程执行完毕,自然会停止
异常退出
设置了标志位,当标志位为false时退出
线程中断退出
(这也是一道常见面试题)
线程函数执行完毕正常退出和发生异常被迫退出都不受我们控制,下面讨论控制线程停止的方式。
设置退出标志位
package com.sync.demo; import javax.swing.text.html.HTML.Tag; public class Demo5 { public static void main(String[] args) { ThreadC c = new ThreadC(); Thread thread = new Thread(c); thread.start(); try { Thread.sleep(3000); c.setTag(false); } catch (InterruptedException e) { e.printStackTrace(); } } static class ThreadC implements Runnable{ private boolean Tag = true; public boolean isTag() { return Tag; } public void setTag(boolean tag) { Tag = tag; } public ThreadC() { super(); } @Override public void run() { while (true) { if (!Tag) { System.out.println("=========退出============"); return ; }else { System.out.println("=========run============"); } } } } }
线程中断
java提供了线程中断机制,可以利用线程中断机制来结束线程,运行过程中检查线程是否被中断或者捕获InterruptedException异常。
判断中断的两种方式:
Thread.interrupted(); 可以设置中断的值为false
isInterrupted()
检查中断:
public class Demo5 { public static void main(String[] args) { ThreadD threadD = new ThreadD(); threadD.start(); try { Thread.sleep(3000); threadD.interrupt(); } catch (InterruptedException e) { e.printStackTrace(); } } static class ThreadD extends Thread{ public ThreadD() { super(); } @Override public void run() { while (true) { if (isInterrupted()) { System.out.println("=========退出============"); return ; }else { System.out.println("=========run============"); } } } } }
利用捕获中断停止线程:
public class Demo5 { public static void main(String[] args) { ThreadE threadE = new ThreadE(); threadE.start(); try { Thread.sleep(3000); threadE.interrupt(); } catch (InterruptedException e) { e.printStackTrace(); } } static class ThreadE extends Thread { public ThreadE() { super(); } @Override public void run() { try { test1(); } catch (InterruptedException e) { e.printStackTrace(); } } private void test1() throws InterruptedException { while (true) { if (!isInterrupted()) { System.out.println("=========run============"); } else { throw new InterruptedException(); } } } } }
相关推荐
android下vulkan与opengles纹理互通
talkchan · 1158浏览 · 2020-11-23 10:37:39
Android 使用RecyclerView实现轮播图
奔跑的男人 · 2166浏览 · 2019-05-09 17:11:13
微软发布新命令行工具 Windows Terminal
吴振华 · 860浏览 · 2019-05-09 17:15:04
在华为写了十几年代码,我为什么还没有被拿去“祭天”
追忆似水年华 · 1193浏览 · 2019-05-09 17:22:20
android 通过修改图片像素实现CircleImageView
吴振华 · 1118浏览 · 2019-05-09 22:26:56
分类专栏
最新发布
最热排行
0评论