[英]Make Java Runnable run continuously
How to make a class
that implements a java.lang.Runnable
interface to run continuously without blocking the whole application. 如何使实现java.lang.Runnable
接口的class
在不阻塞整个应用程序的情况下连续运行。
For example: 例如:
private void startHandler(UsbDevice d) {
if (mLoop != null) {
mConnectionHandler.onErrorLooperRunningAlready();
return;
}
mLoop = new UsbRunnable(d);
mUsbThread = new Thread(mLoop);
mUsbThread.start();
}
Need to make the mLoop
's run() method to run continuously. 需要使mLoop
的run()方法连续运行。 UsbRunnable implements the Runnable interface. UsbRunnable实现了Runnable接口。
How to make a class that implements a java.lang.Runnable interface to run continuously without blocking the whole application. 如何使实现java.lang.Runnable接口的类在不阻塞整个应用程序的情况下连续运行。
You need two things: 你需要两件事:
run()
method run()
方法中的循环 public class USBRunnable implements Runnable {
public void run() {
while (isRunning) {
data = readFromUSBDevice(); // waits until data is available, returns the data read
processData(data);
}
}
}
The typical way is to put a loop in run
: 典型的方法是run
循环:
public void run() {
while (!terminationCondition) {
// Do work
}
}
run
should model the total work the Runnable
needs to do, not just one iteration of that work. run
应该模拟Runnable
需要做的总工作,而不仅仅是该工作的一次迭代。 So if it needs to do repeated work until it's stopped, you use a loop to do exactly that. 因此,如果它需要重复工作直到它停止,你使用循环来做到这一点。
Can have a while (true){......} Loop inside the run method of the class that implements runnable. 可以有一段时间(true){......}循环实现runnable的类的run方法。 Can mark this thread as deamon. 可以将此主题标记为deamon。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.