使 Java Runnable 持续运行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15199920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:49:22  来源:igfitidea点击:

Make Java Runnable run continuously

java

提问by quarks

How to make a classthat implements a java.lang.Runnableinterface to run continuously without blocking the whole application.

如何让一个class实现了java.lang.Runnable接口的程序在不阻塞整个应用程序的情况下连续运行。

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. UsbRunnable implements the Runnable interface.

需要使mLoop的 run() 方法连续运行。 UsbRunnable 实现了 Runnable 接口。

回答by Andreas Fester

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:

你需要两件事:

  • A loop inside the run()method
  • A call which blocks, usually by communicating with your device
  • run()方法内部的循环
  • 通常通过与您的设备通信来阻止的呼叫
public class USBRunnable implements Runnable {

  public void run() {
      while (isRunning) {
          data = readFromUSBDevice();  // waits until data is available, returns the data read
          processData(data);
      }
   }
}

回答by user1441664

Can have a while (true){......} Loop inside the run method of the class that implements runnable. Can mark this thread as deamon.

在实现 runnable 的类的 run 方法中可以有一个 while (true){......} 循环。可以将此线程标记为守护进程。

回答by T.J. Crowder

The typical way is to put a loop in run:

典型的方法是放入一个循环run

public void run() {
    while (!terminationCondition) {
        // Do work
    }
}

runshould model the total work the Runnableneeds to do, not just one iteration of that work. So if it needs to do repeated work until it's stopped, you use a loop to do exactly that.

run应该对Runnable需要做的全部工作进行建模,而不仅仅是该工作的一次迭代。因此,如果它需要重复工作直到停止,您可以使用循环来做到这一点。