gpt4 book ai didi

java - 中断线程后执行操作

转载 作者:行者123 更新时间:2023-12-01 13:44:51 25 4
gpt4 key购买 nike

我有两个线程,threadOne 等待用户输入,threadTwo 在收到用户输入之前使用 interrupt() 方法中断它。我想在成功中断 threadOne 后执行一段代码。我尝试通过在 threadOne 的 run() 方法中捕获 ClosedByInterruptException 来实现这一点,但编译器给出以下错误:

异常 ClosedByInterruptException 已被捕获

代码如下:

class InputInterruption {
public static void main(String[] args) {

final Thread t2 = new Thread() {
public void run() {
try {
System.out.print("make a selection: ");
String userInput = (new BufferedReader(new InputStreamReader(System.in))).readLine();
System.out.println(String.format("user input: %s", userInput));
} catch (IOException e) {
System.out.println("Oops..somethign went wrong.");
System.exit(1);
} catch(ClosedByInterruptException e) {
System.out.println("Successfully interrupted");
}
}
};
t2.start();



Thread t1 = new Thread() {
public void run() {
try {
sleep(1000);
System.out.println("interrupting InputStreamReader");
t2.interrupt();
System.exit(0);
} catch (InterruptedException e) {
System.out.println("Successfully interrupted");
}
}
};
t1.start();
}

}

最佳答案

ClosedByInterruptionException 扩展了 IOException。尝试切换 catch 语句的顺序。

关于java - 中断线程后执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20434363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com