日期:2014-05-20  浏览次数:20792 次

求教!!!!!!!!!!!!!!!!!
让一个程序不停的在那运行,直到命令行输入   quit打断,怎么实现,谢谢

PS:不是每次都要去Scanner   一下进行判断,而是我不输   quit它就不停,一直循环,直到我输   quit

------解决方案--------------------
启动一个键盘监听适配器来监听是否有键盘输入,如果有则判断是否是quit
具体的操作是实现KeyListener接口,可以用KeyAdapter类,它已经实现了KeyListener接口
------解决方案--------------------
class Monitor implements Runnable {
String keys = " ";
Test t;

public Monitor(Test t) {
this.t = t;
}

public void run() {
while (true) {
try {
int in = System.in.read();
if (in == 10) {
if (keys.equals( "quit ")) {
t.run = false;
break;
}
keys = " ";
}
else {
char c = (char)(in & 0xff);
if (c > 'a ' && c < 'z ')
keys += c;
}
} catch (Exception e) {

}
}

}}


public class Test implements Runnable{
public boolean run = true;

public Test() {
}

public static void main(String[] args) {
Thread thread = new Thread(new Test());
thread.start();
}

public void run() {
Thread thread = new Thread(new Monitor(this));
thread.start();
while (run) {
try {
Thread.sleep(1000);
System.out.println( "running... ");
} catch (Exception e) {

}
}

}

}