[英]How do i interrupt a thread from another thread in java?
I'm writing a simple program.我正在编写一个简单的程序。 A thread will run infinitely printing, say counting:
一个线程将无限运行打印,比如说计数:
class MyThread extends Thread {
private int count = 0;
public void run() {
while(true) {
System.out.println(count++);
try { currentThread().sleep(2000); }
catch (InterruptedException ignored) { }
}
}
}
until user gives any (String) input of more than 2 letters:直到用户提供超过 2 个字母的任何(字符串)输入:
class MyThreadStopper extends Thread {
MyThread obj ;
MyThreadStopper(MyThread obj) {
this.obj = obj;
}
public void run() {
String userInput ;
while(true) {
userInput = (new Scanner(System.in)).next();
if( userInput.length() > 2) {
obj.interrupt();
currentThread().interrupt();
}
try{ currentThread().sleep(1000); }
catch (InterruptedException ignored) { }
}
}
}
Used one thread for printing and another thread of different class to get input.使用一个线程进行打印,另一个线程使用不同的 class 来获取输入。 I'm not sure where i am doing it wrong.
我不确定我在哪里做错了。
class temp {
public static void main(String[] args) {
MyThread obj = new MyThread();
MyThreadStopper objStop = new MyThreadStopper(obj);
obj.start();
objStop.start();
}
}
As it keeps printing infinitely, even though i tried printing the userInput
and removing if
after the userInput
.由于它一直在无限打印,即使我尝试打印
userInput
并在userInput
之后删除if
。
you are ignoring the interrupt: you could stop the thread when it is interrupted (or do something else, depeding on the requirements)您忽略了中断:您可以在线程中断时停止线程(或根据要求执行其他操作)
class MyThread extends Thread {
private int count = 0;
public void run() {
while(!interrupted) {
System.out.println(count++);
try { currentThread().sleep(2000); }
catch (InterruptedException e) {
// we got interrupted, time to do something
interrupted = true;
}
}
}
}
generally interrupting a thread to stop it is rarely a good solution.通常中断一个线程来停止它很少是一个好的解决方案。
class MyThread extends Thread {
private int count = 0;
public void run() {
while(true) {
System.out.println(count++);
try { currentThread().sleep(2000); }
catch (InterruptedException ignored) {
System.out.println("Interrupted");
break;
}
}
}
}
You were not doing anything once you are catching InterruptedException.一旦你捕捉到 InterruptedException,你就没有做任何事情。 So loop was continuing.
所以循环还在继续。 The above modified code should print "Interrupted" & break.
上面修改后的代码应该打印“Interrupted”&break。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.