简体   繁体   English

我怎样才能重新开始线程?

[英]How can I start thread again?

I know time and time again people have asked how to start a thread after it's been stopped and everyone says you can't.我知道人们一次又一次地询问如何在停止线程后启动线程,每个人都说你不能。 This isn't a duplicate to that because I've found no solution for the problem.这不是重复的,因为我没有找到解决问题的方法。

private void runInBackground() {
    new Thread(new Runnable() {

        @Override
        public void run() {
            while (running) {
                try {
                    checkPixel();
                } catch (AWTException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();
}

@Override
public void nativeKeyPressed(NativeKeyEvent e) {
    // TODO Auto-generated method stub
     System.out.println("Key Pressed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
     if(NativeKeyEvent.getKeyText(e.getKeyCode()).equals("F9")){
         stop();
     }
     else if(NativeKeyEvent.getKeyText(e.getKeyCode()).equals("F10")){

     }

So in my code I'm listening for global key events using JNativeHook.所以在我的代码中,我使用 JNativeHook 监听全局关键事件。 I can successfully stop the checkPixels() using the F9 key but I'm not understanding what I should do using F10 when I wanna start up checkPixel() again.我可以使用 F9 键成功停止checkPixels()但我不明白当我想再次启动checkPixel()时我应该使用 F10 做什么。

checkPixel() basically checks for a change in pixel color checkPixel()基本上检查像素颜色的变化

ANSWERED Added an if statement for my state variable running and keep the while loop true allows me to turn on/off the method while keeping the thread open.回答增加了一个if语句我的状态变量running并保持while循环真正让我打开/关闭的方法,同时保持线程开放。 Thank you Jaboyc谢谢Jaboyc

    private void runInBackground() {
    new Thread(new Runnable() {

        @Override
        public void run() {
            while (true) {
                if(running){
                    try {
                        checkPixel();
                    } catch (AWTException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }).start();
}

Would this work这行得通吗

while (true) {
    if (running) {
        doStuff();
    }
}

in the run method?在运行方法中?

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

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