简体   繁体   English

暂停执行线程,并根据用户输入继续执行

[英]Pause Thread execution, and resume based on user input

I have a thread which impelments JNativeHook.jar which creates a global keybourd and mouse listener. 我有一个线程会推动JNativeHook.jar的创建一个全局键盘和鼠标侦听器。 Based on user input the thread can act as such. 根据用户输入,线程可以这样操作。

I would like to stop all Thread execution when a user (let's say) presses VK_SPACE. 我想在用户(例如)按下VK_SPACE时停止所有线程执行。 I would want to spawn another Thread which also watches the keyboard, and when it gets a VK_SPACE again it will tell the main Thread to resume. 我想生成另一个也监视键盘的线程,当它再次获得VK_SPACE时,它将告诉主线程恢复。

Is this sort of action possible in Java, and how might it look? Java中是否可以执行这种操作,它的外观如何?

Here is some code to work with and JNativeHook .jar 这是和JNativeHook .jar一起使用的一些代码

CODE: 码:

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){}
}

Instead of running around trying to lock on different monitors and stuff, I would, personally, place a flag in GlobalKeyListenerExample that would, when a certain key combination is detected, start ignoring any more incoming keys until a certain key combination was raised. 我个人不是在尝试锁定不同的监视器和其他东西,而是在GlobalKeyListenerExample中放置一个标志,该标志将在检测到某个特定的组合键时开始忽略更多传入的键,直到引发特定的组合键为止。

The problem you face currently is knowing 1- What thread you are in and what effect "pausing" it might have and 2- Knowing when the "un-pause" combination is raised...cause you're no longer listening to key events (because you may have inadvertently stopped the thread that the native interface was using to raise the events with...) 您当前面临的问题是知道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...
        }
    }
}

Updated 更新

Just as a side note...this 恰如其分...

public void run()
{
    while(alive){}
}

Isn't a good idea. 这不是一个好主意。 Basically, it leaves the thread in "running" state, consuming CPU cycles unnecessarily. 基本上,它使线程处于“运行”状态,不必要地消耗了CPU周期。 In your case, I'm not sure how you would actually be able to correct for it... 就您而言,我不确定您实际上将如何进行纠正...

in method run: 在方法运行中:

public void run(){
 while(me!=null) //execute forever
   try{
      Thread.sleep(5);
      if(!alive) continue; //define pause

      ... do somthing   
   catch(Exception e){}

We need to "thread" stay all the time checking on whether this "pause". 我们需要一直“保持线程”状态,以检查是否存在“暂停”状态。

Important! 重要! is recommended to use a method public synchronized void setAlive (boolean value) to avoid conflicts of "thread" 建议使用public synchronized void setAlive (boolean value)来避免“线程”冲突

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM