【发布时间】:2014-03-30 17:22:57
【问题描述】:
我正在编写一个涉及使用线程更新 UI 的 java swing 程序,
线程中的run函数包含一个while循环和一个睡眠定时器,
我想在用户按下例如ctrl+c 时终止while 循环或线程本身。该线程包含一个睡眠命令,我不希望用户必须按住ctrl+c 才能终止,我只想能够使用这些键一次。
这怎么可能?
public static void main(String[] args) {
.......//Code to set up window
Thread thread = new Thread(){
@Override
public void run() {
while(user has not terminated the program with ctrl+c){
//Do Something
try{
Thread.sleep(5000);
}catch(InterruptedException e){
}
}
}
};
.......//Code to start thread
}
【问题讨论】:
-
使用
keyListener并在操作中使用interrupt the thread或使用condition inside while as false! -
它似乎就像您在询问在运行程序的终端上输入 ctrl+c 吗?这将终止 JVM 和所有线程。如果您的意思是您实际上希望用户能够在您的 GUI 应用程序获得焦点时按 ctrl+c ......那么发布的答案应该会有所帮助。
标签: java multithreading keylistener