multithreading - 线程被中断后执行
问题描述
一个线程正在执行打印从 0 到 n 的数字的任务,并在每个打印语句后休眠 4000 毫秒。中间线程的某个地方被打断了。现在,当同一个线程开始执行时,它将从哪里开始,它会再次开始打印从 0 到 n 的数字,还是从它被中断的地方打印数字。在这两种情况下,原因是什么以及如何处理?
public class Main {
public static void main(String[] args) throws InterruptedException {
SleepTest sleepTest = new SleepTest();
Thread thread = new Thread(sleepTest);
thread.start();
thread.interrupt();
}
}
public class SleepTest implements Runnable{
static int sleep = 10;
public void run(){
for (int i =0; i<10; i++){
System.out.println(i);
try {
Thread.currentThread().interrupt();
Thread.sleep(4000);
} catch (InterruptedException exception) {
exception.printStackTrace();
}
System.out.println(Thread.interrupted());
}
}
解决方案
所做的只是将字段的Thread.currentThread().interrupt()
值更新interrupted
为.true
让我们看看程序的流程以及interrupted
字段是如何赋值的:
public class Main {
public static void main(String[] args) throws InterruptedException {
SleepTest sleepTest = new SleepTest();
Thread thread = new Thread(sleepTest, "Sub Thread"); // Give a name to this thread
thread.start(); // main thread spawns the "Sub Thread". Value of "interrupted" - false
thread.interrupt(); // called by main thread. Value of "interrupted" - true
}
}
public class SleepTest implements Runnable{
static int sleep = 10;
public void run(){
System.out.println(Thread.currentThread().getName()+" "+Thread.interrupted()); // prints "Sub Thread true"
for (int i =0; i<10; i++){
System.out.println(i);
try {
Thread.currentThread().interrupt(); // no matter what value is for interrupted, it is assigned the value "true"
Thread.sleep(4000); // Can't call sleep with a "true" interrupted status. Exception is thrown. Note that, when the exception is thrown, the value of interrupted is "reset", i.e., set to false
} catch (InterruptedException exception) {
exception.printStackTrace(); // whatever
}
System.out.println(Thread.interrupted()); // returns the value of interrupted and resets it to false
}
}
回答
它将从哪里开始,它会再次开始打印从 0 到 n 的数字,还是从中断的地方打印数字。
调用中断不会导致它重新开始,因为它在此调用中所做的一切都将值设置interrupted
为 false (并且不修改任何其他内容)。
推荐阅读
- python - 将所有数据框元素转换为字符串,包括列和索引
- typescript - TypeScript 接口的语法
- javascript - SyntaxError:预期的表达式,得到 '}' -php html 和 javascript
- git - 如何使用压缩文件+演示分支管理生产分支
- c# - 无法通过组合和文本框进行选项卡
- google-app-maker - 如何在 appmaker 编辑器中更改用户
- php - PHP 7.1 - 错误
- sql - 查询以将订阅者状态更新到 Salesforce 营销云中的列表
- apache - 如何仅在两个物理帧上配置具有冗余的 Apache Zookeeper?
- c# - 在 Selenium 中单击具有相同标签的按钮