正在回答
2回答
同学你好,interrupt();方法可以理解为是中断线程,他不能中断正在运行中的线程,可以改变运行状态
如果要使用interrupt();方法使正在运行的线程停止可以结合isInterrupted()方法,该方法是用来判断此线程是否被中断,当isInterrupted()为true时,可以添加个return来结束该线程
如:

综上,interrupt()在普通线程的使用上也是有意义的,但他是用来中断线程而已
祝学习愉快
好帮手慕阿园
2020-10-21 13:48:23
同学你好
1,可以设置一个flag标志位,停止线程
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 (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
StopThread st = new StopThread();
Thread th = new Thread(st);
th.start();
try {
Thread.sleep(5500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// th.stop();
st.stopThread();
}
}2,可以使用 interrupt 方法中断线程,比如:
public class InterruptThread extends Thread{
public static void main(String[] args) {
try {
InterruptThread t = new InterruptThread();
t.start();
Thread.sleep(2000);
t.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
super.run();
for(int i = 0; i <= 200000; i++) {
System.out.println("i=" + i);
}
}
}祝学习愉快
java工程师2020版
- 参与学习 人
- 提交作业 9410 份
- 解答问题 16556 个
综合就业常年第一,编程排行常年霸榜,无需脱产即可学习,北上广深月薪过万 无论你是未就业的学生还是想转行的在职人员,不需要基础,只要你有梦想,想高薪
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星