[英]Pause Thread execution, and resume based on user input
我有一个线程会推动JNativeHook.jar的创建一个全局键盘和鼠标侦听器。 根据用户输入,线程可以这样操作。
我想在用户(例如)按下VK_SPACE时停止所有线程执行。 我想生成另一个也监视键盘的线程,当它再次获得VK_SPACE时,它将告诉主线程恢复。
Java中是否可以执行这种操作,它的外观如何?
这是和JNativeHook .jar一起使用的一些代码
码:
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
public class GlobalKeyListenerExample implements NativeKeyListener
{
public void nativeKeyPressed(NativeKeyEvent e)
{
System.out.println("Key Pressed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
if (e.getKeyCode() == NativeKeyEvent.VK_ESCAPE)
{
GlobalScreen.unregisterNativeHook();
}
if (e.getKeyCode() == NativeKeyEvent.VK_SPACE)
{
WatchForMe w = new WatchForMe(this);
w.start();
this.wait();
}
}
public void nativeKeyReleased(NativeKeyEvent e){}
public void nativeKeyTyped(NativeKeyEvent e){}
public static void main(String[] args)
{
try
{
GlobalScreen.registerNativeHook();
}
catch (NativeHookException ex)
{
System.err.println("There was a problem registering the native hook.");
System.exit(1);
}
//Construct the example object and initialze native hook.
GlobalScreen.getInstance().addNativeKeyListener(new GlobalKeyListenerExample());
}
}
public class WatchForMe implements NativeKeyListener
{
boolean alive = true;
Thread me = null;
public WatchForMe(Thread me)
{
if(me == null) return;
this.me = me;
GlobalScreen.getInstance().addNativeKeyListener(this);
}
public void nativeKeyPressed(NativeKeyEvent e)
{
System.out.println("Key Pressed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
if (e.getKeyCode() == NativeKeyEvent.VK_SPACE)
{
me.notify();
alive = false;
}
}
public void run()
{
while(alive){}
}
public void nativeKeyReleased(NativeKeyEvent e){}
public void nativeKeyTyped(NativeKeyEvent e){}
}
我个人不是在尝试锁定不同的监视器和其他东西,而是在GlobalKeyListenerExample
中放置一个标志,该标志将在检测到某个特定的组合键时开始忽略更多传入的键,直到引发特定的组合键为止。
您当前面临的问题是知道1-您正在使用哪个线程以及该线程可能具有“暂停”的作用,并且2-知道何时会出现“取消暂停”组合...因为您不再在听关键事件(因为您可能无意中停止了本机接口用来引发事件的线程...)
public void nativeKeyPressed(NativeKeyEvent e)
{
System.out.println("Key Pressed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
if (isPaused) {
if (e.getKeyCode == UNPAUSE_KEY_CODE) {
isPaused = false;
}
} else {
if (e.getKeyCode == PAUSE_KEY_CODE) {
isPaused = true;
} else {
// Handle other key strokes...
}
}
}
更新
恰如其分...
public void run()
{
while(alive){}
}
这不是一个好主意。 基本上,它使线程处于“运行”状态,不必要地消耗了CPU周期。 就您而言,我不确定您实际上将如何进行纠正...
在方法运行中:
public void run(){
while(me!=null) //execute forever
try{
Thread.sleep(5);
if(!alive) continue; //define pause
... do somthing
catch(Exception e){}
我们需要一直“保持线程”状态,以检查是否存在“暂停”状态。
重要! 建议使用public synchronized void setAlive (boolean value)
来避免“线程”冲突
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.