The following snippet is a thread named “Foo” that sleeps for 1 minute and then copies the data typed in 1 minute to a log file.
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();
}
}
I will describe one situation :
Foo thread has finished copying all the data typed in last one minute and it has been 30 seconds since it is asleep. This thread unaware of the situation that several keys are being tapped when it is asleep,will never be able to copy the key strokes into the log file when one presses System.exit(0).
Is there any way I can interrupt this thread i.e awake it and ask it to copy the data to the log file.
Please discuss how should I approach this problem.
The situation in the question :
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 ?
You’re part way there…
What you need to is provide a way to terminate the loop…
You should also know that the JVM will not exit until all non-daemon threads have completed (under normal shutdown). This means you can call
System.exit(0)and the JVM will not terminate until the logger thread has terminated.You could use this, but attaching a shut down hook which would have the capacity to call the
disposemethod on the logger thread…just a thought