我正在写一个简单的程序。
class MyThread extends Thread {
private int count = 0;
public void run() {
while(true) {
System.out.println(count++);
try { currentThread().sleep(2000); }
catch (InterruptedException ignored) { }
}
}
}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) { }
}
}
}使用一个线程打印,另一个不同类的线程获取输入。我不确定我在哪里做错了。
class temp {
public static void main(String[] args) {
MyThread obj = new MyThread();
MyThreadStopper objStop = new MyThreadStopper(obj);
obj.start();
objStop.start();
}
}因为它一直在无限打印,即使我尝试打印userInput并在userInput之后删除if。
发布于 2021-03-14 12:08:57
你忽略了中断:你可以在线程被中断时停止它(或者做一些其他的事情,取决于需求)
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;
}
}
}
}通常,通过中断线程来停止它通常不是一个好的解决方案。
发布于 2021-03-14 12:10:03
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;
}
}
}
}一旦你抓到了InterruptedException,你什么也没做。所以循环还在继续。上面修改过的代码应该打印"Interrupted“& break。
https://stackoverflow.com/questions/66620943
复制相似问题