下面的代码片段是一个名为“Foo”的线程,它会休眠 1 分钟,然后将1 分钟内输入的数据复制到日志文件中。
while(isStarted) {
try {
Thread.sleep(60000); // sleep for 1 minute
ArrayList<String> keyStrokeList = nativeMethods.getKeyStrokeList();
int result = copy.copyToLogFile(keyStrokeList);
System.out.println(result);
} catch(Exception exc) {
exc.printStackTrace();
}
}
我将描述一种情况:
Foo线程已经完成了对最后一分钟输入的所有数据的复制,并且从休眠到现在已经 30 秒。该线程不知道在睡眠时有几个键被敲击的情况,永远无法将击键复制到日志文件中System.exit(0)
。
有什么办法可以中断这个线程,即唤醒它并要求它将数据复制到日志文件。
请讨论我应该如何解决这个问题。
问题中的情况:
loop started
thread is sleeping and will sleep for 1 minute
after a minute,it gets the keys tapped in the last 1 minute and copies all that
to a file
Thread sleeps again..and will sleep for 1 minute before it copies the keystrokes
It has been about 30 seconds and thread will sleep for 30 seconds more before it starts
copying the key strokes
suddenly the user presses exit button in the application
The user wants that key strokes be recorded till the second he presses exit
I cannot do System.exit(0) before checking the thread is asleep or not
How do I do this. Should I awake it or make a different call to the list and get the
key strokes because they are being recorded ? And how shall I awake it ?