Class 运行 在后台

Class Run in Background

我在 java 中制作应用程序 SE.And 我想制作一个 class 始终在后台 运行 并使用它自己的线程而不是我的主线程主要 class 使用。这在 java SE 中可能吗?与 android 一样,我们可以在服务 class.

的帮助下完成此任务

当然可以在 java SE 中完成。 您需要实现 Runnable 并将代码放入方法 运行()

例如:

public final class ThreadExample implements Runnable {
  public static void main(String[] args) {
    Thread thread = new Thread(new ThreadExample());
    thread.start();
    System.out.println("Exit the main");
  }

  public void run() {
    while (true) {
      System.out.println("Current time: " + (new Date()).getTime());
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        System.out.println("Error: " + e.getMessage());
      }
    }
  }
}