[英]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.