我正在制作一个Java应用程序,该应用程序可以在热键组合上进行操作。我有一个无限的循环等待热键输入关闭,但它使该应用程序成本很高。
以下是我的代码以最简单的方式外观:
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
关键字的信息。只需谷歌,您就应该找到大量的示例和教程。
这应该解决您的案件:
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();
}
}
}
无限,而循环可以消耗大量的系统资源。建议使用等待和通知。另外,您还必须将布尔 volatile
声明为否则,不能保证一个线程所做的更改由另一个线程拾取。下面是一个在单独的线程中执行某些操作的示例,直到被用户输入(在这种情况下输入)中断为直到被调用线程中断为止。另请参见Oracle此处的示例
import java.util.Scanner;
public class WaitTest implements Runnable {
private volatile boolean shutdown = false;
public static void main(String[] args) {
WaitTest w = new WaitTest();
new Thread(w).start();
System.out.println("Press any key to interrupt");
Scanner sc = new Scanner(System.in);
sc.nextLine();
w.triggerShutDown();
}
@Override
public void run() {
while (!shutdown) {
synchronized (this) {
try {
System.out.println("doing some silly things");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("Server shutdown successfully");
}
public synchronized void triggerShutDown() {
this.shutdown = true;
notify();
}
}