我试图创建一个对我的代码调试有用的引擎,但是似乎它需要自己调试...主要功能是javax.swing-applikilation,从中可以打开包的其他子类。我试图在Shell中放入输入线程(我正在使用Eclipse),但是问题是它在打开后 second 无效。第一次!我没有发现任何资源泄漏。不知何故,它只是一次又一次地输出一个空行。中断必须与输入类的打开和关闭有关,但是我唯一能找到的是关于如何使用或终止线程的教程(我在那儿做的事情,请以InterruptedException结尾看待) 。 很奇怪的是,它确实没有第二次打开这种半错误状态。通常,它在第二次打开时会输出Exception,但是我将其编码为不进行任何操作。
代码:
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class Commander extends Thread {
/**
* @Author Ninto
*/
static String Input = "";
private static Logger log=null;
boolean running = true;
boolean scanning = true;
Commander(){
setDaemon(false);
}
public Commander(){}
@Override
public void run() {
running = true;
scanning = true;
input in = new input(); //Opens the Thread of the Subclass input
in.start();
while(running) {
TimeUnit.MILLISECONDS.sleep(25);
if(!Input.equals("")) {
switch(Input) {
case "something_else": break; //Do the debug there, like controlling the variables used by other classes
case "exit" : running = false; break; //Should close this Class & subclasses
case "stop" : System.exit(0); break; //Ends the program. Not to use!
}
}
Input = "";
scanning = true;
}
in.interrupt(); //Should break the Subclass - thread
TimeUnit.MILLISECONDS.sleep(100);
running = false;
}
class input extends Thread {
input() {setDaemon(true);} //To close the Thread with the exit of the Programm if still existing
private String Input = " ";
@Override
public void run() {
Scanner sc = new Scanner(System.in);
try {
while(true) {
if(isInterrupted()||!running) {
log.Log2("Spacecommander/Input","Stop Thread");
sc.close();
return;}
while(!scanning) {TimeUnit.MILLISECONDS.sleep(125);}
TimeUnit.MILLISECONDS.sleep(250);
try{this.Input = sc.nextLine();}
catch(NoSuchElementException e) {scanning = false;}
/*There does it break the Second time the Thread is used.
Another start of the Thread does the Same, only the first Time does it work.*/
Commander.Input = this.Input;
log.Log2("INPUT",Input);
this.Input = "";
scanning=false;}
}
catch(InterruptedException e) { //if this is called, it closes the Scanner and should exit the Programm.
sc.close();}
sc.close();
}
}
}
答案 0 :(得分:0)
认为问题在于对sc.close()
的各种调用。由于Scanner
是针对System.in
创建的,因此也会被关闭。
一旦删除close()
调用,Eclipse将警告您有关资源泄漏的信息-在您的情况下,可以忽略此信息,例如:
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
在这种情况下的另一种常见技术是保留Scanner
实例供下一个线程使用-例如在共享的静态变量中。