我怎样才能再次启动线程?

时间:2015-07-29 15:53:31

标签: java multithreading keylistener

我一次又一次地知道人们已经问过如何在它停止后开始一个线程并且每个人都说你不能。这并不重复,因为我找不到问题的解决方案。

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

     }

因此,在我的代码中,我正在使用JNativeHook监听全局关键事件。我可以使用F9键成功停止checkPixels(),但是当我想再次启动checkPixel()时,我不明白我应该使用F10做什么。

checkPixel()基本上检查像素颜色的变化

ANSWERED 为我的状态变量running添加了if语句并保持while循环为true允许我在保持线程打开的同时打开/关闭方法。谢谢 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();
}

1 个答案:

答案 0 :(得分:2)

这会有效吗

<rect class="vis-graph-group0 vis-bar" height="33.33333333333337" width="50" y="300" x="1956.375">
</rect>
<rect class="vis-graph-group0 vis-point" height="0" width="0" y="300" x="1981.375">
</rect>
<text y="300" x="1956.375">10</text>
<rect class="vis-graph-group1 vis-bar" height="40.33333333333337" width="50" y="259.66666666666663" x="1956.375">
</rect>
<rect class="vis-graph-group1 vis-point" height="0" width="0" y="293" x="1981.375">
</rect>
<text y="293" x="1956.375">12</text>
<rect class="vis-graph-group2 vis-bar" height="73.33333333333337" width="50" y="186.33333333333326" x="1956.375">
</rect>
<rect class="vis-graph-group2 vis-point" height="0" width="0" y="260" x="1981.375">
</rect>
<text y="260" x="1956.375">22</text>

在run方法中?