gpt4 book ai didi

java - 当用户按下退出键时,如何中断线程并要求其完成工作?

转载 作者:行者123 更新时间:2023-12-01 15:07:35 24 4
gpt4 key购买 nike

下面的代码片段是一个名为“Foo”的线程,它 hibernate 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 线程已完成复制最后一分钟内输入的所有数据,距离 hibernate 已过去 30 秒。该线程不知道在 sleep 时有多个按键被敲击的情况,当按下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 ?

最佳答案

你已经成功了......

while(isStarted) {
try {
Thread.sleep(60000); // sleep for 1 minute
} catch(InterruptedException exc) {
exc.printStackTrace();
}
ArrayList<String> keyStrokeList = nativeMethods.getKeyStrokeList();
int result = copy.copyToLogFile(keyStrokeList);
System.out.println(result);
}

您需要提供一种终止循环的方法...

public void dispose() {
isStarted = false;
interrupt();
try {
join();
} catch(InterruptedException exc) {
exc.printStackTrace();
}
}

您还应该知道,在所有非守护线程完成之前(正常关闭情况下),JVM 不会退出。这意味着您可以调用 System.exit(0) 并且 JVM 在记录器线程终止之前不会终止。

您可以使用它,但附加一个 shut down hook它将有能力在记录器线程上调用 dispose 方法...只是一个想法

关于java - 当用户按下退出键时,如何中断线程并要求其完成工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12767869/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com