簡體   English   中英

我怎樣才能重新開始線程?

[英]How can I start thread again?

我知道人們一次又一次地詢問如何在停止線程后啟動線程,每個人都說你不能。 這不是重復的,因為我沒有找到解決問題的方法。

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()基本上檢查像素顏色的變化

回答增加了一個if語句我的狀態變量running並保持while循環真正讓我打開/關閉的方法,同時保持線程開放。 謝謝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();
}

這行得通嗎

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

在運行方法中?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM