本网站(662p.com)打包出售,且带程序代码数据,662p.com域名,程序内核采用TP框架开发,需要联系扣扣:2360248666 /wx:lianweikj
精品域名一口价出售:1y1m.com(350元) ,6b7b.com(400元) , 5k5j.com(380元) , yayj.com(1800元), jiongzhun.com(1000元) , niuzen.com(2800元) , zennei.com(5000元)
需要联系扣扣:2360248666 /wx:lianweikj
如何结束线程-线程中断
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
Facebook 停止屏蔽部分区块链广告

· 746浏览 · 2019-05-09 17:20:08
加载中

0评论

评论
分类专栏
小鸟云服务器
扫码进入手机网页