我正在制作一个 Java 应用程序,它可以对热键组合执行某些操作。我有一个无限的 while 循环来等待 HotKey 输入关闭,但这使得应用程序非常耗费 CPU 时间。
以下是我的代码最简单的样子:
static boolean isOpen = true;
void main()
{
....
add SomeHotKeyListener();
....
while(isOpen)
{ }
releaseResources();
}
void onHotKey(int hotKeyIdentifier)
{
if(hotKeyIdentifier == something)
do something;
if(hotKeyIdentifier == something)
isOpen = false;
}
我需要一种多线程方法来实现这一点,或者如果有人有更好的方法可以适应。
最佳答案
我建议您阅读 Java 中的 synchronized
关键字。只是Google it ,你应该找到大量的例子和 tutorials .
这应该可以解决您的问题:
static boolean isOpen = true;
static Object lock = new Object();
void main()
{
....
add SomeHotKeyListener();
....
synchronized(lock)
{
while(isOpen)
{
try {
lock.wait()
} catch(InterruptedException e) {
}
}
}
releaseResources();
}
void onHotKey(int hotKeyIdentifier)
{
if(hotKeyIdentifier == something)
do something;
if(hotKeyIdentifier == something)
{
synchronized(lock)
{
isOpen = false;
lock.notify();
}
}
}
关于java - java中一个线程的输入来自另一个线程的无限等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21398907/