Java while循环和线程! [重复]

时间:2022-05-25 21:02:11

This question already has an answer here:

这个问题在这里已有答案:

I have a program that continually polls the database for change in value of some field. It runs in the background and currently uses a while(true) and a sleep() method to set the interval. I am wondering if this is a good practice? And, what could be a more efficient way to implement this? The program is meant to run at all times.

我有一个程序,不断轮询数据库以获取某些字段值的变化。它在后台运行,目前使用while(true)和sleep()方法来设置间隔。我想知道这是一个好习惯吗?而且,实现这一目标的更有效方法是什么?该计划旨在始终运行。

Consequently, the only way to stop the program is by issuing a kill on the process ID. The program could be in the middle of a JDBC call. How could I go about terminating it more gracefully? I understand that the best option would be to devise some kind of exit strategy by using a flag that will be periodically checked by the thread. But, I am unable to think of a way/condition of changing the value of this flag. Any ideas?

因此,停止程序的唯一方法是对进程ID发出kill。该程序可能处于JDBC调用的中间。我怎么能更优雅地终止它呢?我知道最好的选择是通过使用将由线程定期检查的标志来设计某种退出策略。但是,我无法想到改变这个标志值的方式/条件。有任何想法吗?

13 个解决方案

#1


I am wondering if this is a good practice?

我想知道这是一个好习惯吗?

No. It's not good. Sometimes, it's all you've got, but it's not good.

不,这不好。有时候,这就是你所拥有的一切,但它并不好。

And, what could be a more efficient way to implement this?

而且,实现这一目标的更有效方法是什么?

How do things get into the database in the first place?

事情如何首先进入数据库?

The best change is to fix programs that insert/update the database to make requests which go to the database and to your program. A JMS topic is good for this kind of thing.

最好的更改是修复插入/更新数据库的程序,以发出进入数据库和程序的请求。 JMS主题适用于此类事情。

The next best change is to add a trigger to the database to enqueue each insert/update event into a queue. The queue could feed a JMS topic (or queue) for processing by your program.

下一个最佳更改是向数据库添加触发器,以将每个插入/更新事件排入队列。队列可以提供JMS主题(或队列)以供程序处理。

The fall-back plan is your polling loop.

后备计划是您的轮询循环。

Your polling loop, however, should not trivially do work. It should drop a message into a queue for some other JDBC process to work on. A termination request is another message that can be dropped into the JMS queue. When your program gets the termination message, it absolutely must be finished with the prior JDBC request and can stop gracefully.

但是,您的轮询循环不应该轻松地完成工作。它应该将消息放入队列以供其他JDBC进程处理。终止请求是可以放入JMS队列的另一条消息。当您的程序获得终止消息时,绝对必须使用先前的JDBC请求完成并且可以正常停止。

Before doing any of this, look at ESB solutions. Sun's JCAPS or TIBCO already have this. An open source ESB like Mulesource or Jitterbit may already have this functionality already built and tested.

在执行任何此操作之前,请查看ESB解决方案。 Sun的JCAPS或TIBCO已经有了这个。像Mulesource或Jitterbit这样的开源ESB可能已经构建并测试了这个功能。

#2


This is really too big an issue to answer completely in this format. Do yourself a favour and go buy Java Concurrency in Practice. There is no better resource for concurrency on the Java 5+ platform out there. There are whole chapters devoted to this subject.

在这种格式下完全回答这个问题确实太大了。帮自己一个忙,然后去实践中购买Java Concurrency。在Java 5+平台上没有更好的并发资源。整篇章节专门讨论这个问题。

On the subject of killing your process during a JDBC call, that should be fine. I believe there are issues with interrupting a JDBC call (in that you can't?) but that's a different issue.

关于在JDBC调用期间终止进程的问题,这应该没问题。我相信中断JDBC调用有问题(你不能这样做?)但这是一个不同的问题。

#3


As others have said, the fact that you have to poll is probably indicative of a deeper problem with the design of your system... but sometimes that's the way it goes, so...

正如其他人所说,你必须进行民意调查的事实可能表明你的系统设计存在更深层次的问题......但有时这就是它的方式,所以...

If you'd like to handle "killing" the process a little more gracefully, you could install a shutdown hook which is called when you hit Ctrl+C:

如果你想更好地处理“杀死”这个过程,你可以安装一个关闭钩子,当你按下Ctrl + C时调用它:

volatile boolean stop = false;

Runtime.getRuntime().addShutdownHook(new Thread("shutdown thread") {

    public void run() {

        stop = true;
    }
});

then periodically check the stop variable.

然后定期检查停止变量。

A more elegant solution is to wait on an event:

更优雅的解决方案是等待一个事件:

boolean stop = false;

final Object event = new Object();

Runtime.getRuntime().addShutdownHook(new Thread("shutdown thread") {

    public void run() {

        synchronized(event) {

            stop = true;
            event.notifyAll();
        }
    }
});

// ... and in your polling loop ...
synchronized(event) {

    while(!stop) {

        // ... do JDBC access ...
        try {

            // Wait 30 seconds, but break out as soon as the event is fired.
            event.wait(30000);
        }

        catch(InterruptedException e) {

            // Log a message and exit. Never ignore interrupted exception.
            break;
        }
    }
}

Or something like that.

或类似的东西。

#4


Note that a Timer (or similar) would be better in that you could at least reuse it and let it do with all of the details of sleeping, scheduling, exception handling, etc...

请注意,Timer(或类似的)会更好,因为你至少可以重复使用它,并让它完成睡眠,调度,异常处理等所有细节......

There are many reasons your app could die. Don't focus on just the one.

您的应用可能会死的原因有很多。不要只关注那一个。

If it's even theoretically possible for your JDBC work to leave things in a half-correct state, then you have a bug you should fix. All of your DB work should be in a transaction. It should go or not go.

如果理论上你的JDBC工作甚至可以将事物保持在半正确状态,那么你就应该修复一个bug。您的所有数据库工作都应该在事务中。应该去还是不去。

#5


This is Java. Move your processing to a second thread. Now you can

这是Java。将处理移至第二个线程。现在你可以

  • Read from stdin in a loop. If someone types "QUIT", set the while flag to false and exit.
  • 从循环中的stdin读取。如果有人键入“QUIT”,请将while标志设置为false并退出。

  • Create a AWT or Swing frame with a STOP button.
  • 使用STOP按钮创建AWT或Swing框架。

  • Pretend you are a Unix daemon and create a server socket. Wait for someone to open the socket and send "QUIT". (This has the added bonus that you can change the sleep to a select with timeout.)
  • 假装您是一个Unix守护进程并创建一个服务器套接字。等待有人打开插座并发送“退出”。 (这有额外的好处,您可以将睡眠更改为超时选择。)

There must be hundreds of variants on this.

必须有数百个变种。

#6


Set up a signal handler for SIGTERM that sets a flag telling your loop to exit its next time through.

为SIGTERM设置一个信号处理程序,设置一个标志告诉你的循环下一次退出。

#7


Regarding the question "The program could be in the middle of a JDBC call. How could I go about terminating it more gracefully?" - see How can I abort a running jdbc transaction?

关于“程序可能正在进行JDBC调用的问题。我怎样才能更优雅地终止它?” - 请参阅如何中止正在运行的jdbc事务?

Note that using a poll with sleep() is rarely the correct solution - implemented improperly, it can end up hogging CPU resources (the JVM thread-scheduler ends up spending inordinate amount of time sleeping and waking up the thread).

请注意,使用带有sleep()的轮询很少是正确的解决方案 - 实现不当,最终会占用CPU资源(JVM线程调度程序最终会花费大量时间来休眠和唤醒线程)。

#8


I‘ve created a Service class in my current company’s utility library for these kinds of problems:

我在当前公司的实用程序库中为这些问题创建了一个Service类:

public class Service implements Runnable {

    private boolean shouldStop = false;

    public synchronized stop() {
        shouldStop = true;
        notify();
    }

    private synchronized shouldStop() {
        return shouldStop;
    }

    public void run() {
        setUp();
        while (!shouldStop()) {
            doStuff();
            sleep(60 * 1000);
        }
    }

    private synchronized sleep(long delay) {
        try {
            wait(delay);
        } catch (InterruptedException ie1) {
            /* ignore. */
        }
    }

}

Of course this is far from complete but you should get the gist. This will enable you to simply call the stop() method when you want the program to stop and it will exit cleanly.

当然,这远非完整,但你应该得到要点。这样您就可以在希望程序停止时简单地调用stop()方法,它将干净地退出。

#9


If that's your application and you can modify it, you can:

如果这是您的应用程序并且您可以修改它,您可以:

  • Make it read a file
  • 让它读取文件

  • Read for the value of a flag.
  • 读取标志的值。

  • When you want to kill it, you just modify the file and the application will exit gracefully.
  • 当你想杀死它时,你只需修改文件,应用程序就会正常退出。

Not need to work it that harder that that.

不需要那样努力工作。

#10


You could make the field a compound value that includes (conceptually) a process-ID and a timestamp. [Better yet, use two or more fields.] Start a thread in the process that owns access to the field, and have it loop, sleeping and updating the timestamp. Then a polling process that is waiting to own access to the field can observe that the timestamp has not updated in some time T (which is much greater than the time of the updating loop's sleep interval) and assume that the previously-owning process has died.

您可以将该字段设置为包含(概念上)进程ID和时间戳的复合值。 [更好的是,使用两个或更多字段。]在拥有对字段的访问权限的进程中启动一个线程,并使其循环,休眠和更新时间戳。然后,等待访问该字段的轮询进程可以观察到时间戳在某个时间T内没有更新(这比更新循环的休眠间隔的时间长得多)并且假设先前拥有的进程已经死亡。

But this is still prone to failure.

但这仍然容易失败。

In other languages, I always try to use flock() calls to synchronize on a file. Not sure what the Java equivalent is. Get real concurrency if you at all possibly can.

在其他语言中,我总是尝试使用flock()调用来同步文件。不确定Java等价物是什么。如果你可能的话,获得真正的并发。

#11


I'm surprised nobody mentioned the interrupt mechanism implemented in Java. It's supposed to be a solution to the problem of stopping a thread. All other solutions have at least one flaw, that's why this mechanism is needed to be implemented in the Java concurrency library.

我很惊讶没人提到Java中实现的中断机制。它应该是解决线程停止问题的解决方案。所有其他解决方案至少有一个缺陷,这就是为什么需要在Java并发库中实现此机制的原因。

You can stop a thread by sending it an interrupt() message, but there are others ways that threads get interrupted. When this happens an InterruptedException is thrown. That's why you have to handle it when calling sleep() for example. That's where you can do cleanup and end gracefully, like closing the database connection.

您可以通过向线程发送一条中断()消息来停止线程,但还有其他方法可以使线程中断。发生这种情况时,会抛出InterruptedException。这就是为什么你在调用sleep()时必须处理它的原因。这就是你可以进行清理并优雅地结束的地方,比如关闭数据库连接。

#12


Java9 has another "potential" answer to this: Thread.onSpinWait():

Java9有另一个“潜在的”答案:Thread.onSpinWait():

Indicates that the caller is momentarily unable to progress, until the occurrence of one or more actions on the part of other activities. By invoking this method within each iteration of a spin-wait loop construct, the calling thread indicates to the runtime that it is busy-waiting. The runtime may take action to improve the performance of invoking spin-wait loop constructions.

表示调用者暂时无法进展,直到其他活动发生一个或多个操作为止。通过在自旋等待循环结构的每次迭代中调用此方法,调用线程向运行时指示它正在忙等待。运行时可以采取措施来提高调用自旋等待循环结构的性能。

See JEP 285 for more details.

有关详细信息,请参阅JEP 285。

#13


I think you should poll it with timertask instead.

我认为你应该用timertask轮询它。

My computer is running a while loop 1075566 times in 10 seconds. Thats 107557 times in one second.

我的电脑在10秒内运行了1075566次循环。这是一秒钟107557次。

How often is it truly needed to poll it? A TimerTask runs at its fastest 1000 times in 1 second. You give it a parameter in int (miliseconds) as parameters. If you are content with that - that means you strain your cpu 108 times less with that task.

轮询真正需要多长时间? TimerTask以1秒的最快速度运行1000次。你给它一个int(miliseconds)参数作为参数。如果您对此感到满意 - 这意味着您可以使用该任务减少108倍的CPU压力。

If you would be happy with polling once each second that is (108 * 1000). 108 000 times less straining. That also mean that you could check 108 000 values with the same cpu strain that you had with your one while loop - beause the you dont assign your cpu to check as often. Remember the cpu has a clock cycle. Mine is 3 600 000 000 hertz (cycles per second).

如果您对每秒的轮询(108 * 1000)感到满意。紧张减少108000倍。这也意味着你可以检查108000个值与你的while循环相同的cpu应变 - 因为你不经常分配你的cpu进行检查。记住cpu有一个时钟周期。我的是3 600 000 000赫兹(每秒周期数)。

If your goal is to have it updated for a user - you can run a check each time the user logs in (or manually let him ask for an update) - that would practically not strain the cpu whatsoever.

如果您的目标是为用户更新它 - 您可以在每次用户登录时运行检查(或手动让他请求更新) - 这实际上不会给cpu带来任何压力。

You can also use thread.sleep(miliseconds); to lower the strain of your polling thread (as it wont be polling as often) you where doing.

你也可以使用thread.sleep(miliseconds);降低轮询线程的压力(因为它不经常轮询)你在哪里做。

#1


I am wondering if this is a good practice?

我想知道这是一个好习惯吗?

No. It's not good. Sometimes, it's all you've got, but it's not good.

不,这不好。有时候,这就是你所拥有的一切,但它并不好。

And, what could be a more efficient way to implement this?

而且,实现这一目标的更有效方法是什么?

How do things get into the database in the first place?

事情如何首先进入数据库?

The best change is to fix programs that insert/update the database to make requests which go to the database and to your program. A JMS topic is good for this kind of thing.

最好的更改是修复插入/更新数据库的程序,以发出进入数据库和程序的请求。 JMS主题适用于此类事情。

The next best change is to add a trigger to the database to enqueue each insert/update event into a queue. The queue could feed a JMS topic (or queue) for processing by your program.

下一个最佳更改是向数据库添加触发器,以将每个插入/更新事件排入队列。队列可以提供JMS主题(或队列)以供程序处理。

The fall-back plan is your polling loop.

后备计划是您的轮询循环。

Your polling loop, however, should not trivially do work. It should drop a message into a queue for some other JDBC process to work on. A termination request is another message that can be dropped into the JMS queue. When your program gets the termination message, it absolutely must be finished with the prior JDBC request and can stop gracefully.

但是,您的轮询循环不应该轻松地完成工作。它应该将消息放入队列以供其他JDBC进程处理。终止请求是可以放入JMS队列的另一条消息。当您的程序获得终止消息时,绝对必须使用先前的JDBC请求完成并且可以正常停止。

Before doing any of this, look at ESB solutions. Sun's JCAPS or TIBCO already have this. An open source ESB like Mulesource or Jitterbit may already have this functionality already built and tested.

在执行任何此操作之前,请查看ESB解决方案。 Sun的JCAPS或TIBCO已经有了这个。像Mulesource或Jitterbit这样的开源ESB可能已经构建并测试了这个功能。

#2


This is really too big an issue to answer completely in this format. Do yourself a favour and go buy Java Concurrency in Practice. There is no better resource for concurrency on the Java 5+ platform out there. There are whole chapters devoted to this subject.

在这种格式下完全回答这个问题确实太大了。帮自己一个忙,然后去实践中购买Java Concurrency。在Java 5+平台上没有更好的并发资源。整篇章节专门讨论这个问题。

On the subject of killing your process during a JDBC call, that should be fine. I believe there are issues with interrupting a JDBC call (in that you can't?) but that's a different issue.

关于在JDBC调用期间终止进程的问题,这应该没问题。我相信中断JDBC调用有问题(你不能这样做?)但这是一个不同的问题。

#3


As others have said, the fact that you have to poll is probably indicative of a deeper problem with the design of your system... but sometimes that's the way it goes, so...

正如其他人所说,你必须进行民意调查的事实可能表明你的系统设计存在更深层次的问题......但有时这就是它的方式,所以...

If you'd like to handle "killing" the process a little more gracefully, you could install a shutdown hook which is called when you hit Ctrl+C:

如果你想更好地处理“杀死”这个过程,你可以安装一个关闭钩子,当你按下Ctrl + C时调用它:

volatile boolean stop = false;

Runtime.getRuntime().addShutdownHook(new Thread("shutdown thread") {

    public void run() {

        stop = true;
    }
});

then periodically check the stop variable.

然后定期检查停止变量。

A more elegant solution is to wait on an event:

更优雅的解决方案是等待一个事件:

boolean stop = false;

final Object event = new Object();

Runtime.getRuntime().addShutdownHook(new Thread("shutdown thread") {

    public void run() {

        synchronized(event) {

            stop = true;
            event.notifyAll();
        }
    }
});

// ... and in your polling loop ...
synchronized(event) {

    while(!stop) {

        // ... do JDBC access ...
        try {

            // Wait 30 seconds, but break out as soon as the event is fired.
            event.wait(30000);
        }

        catch(InterruptedException e) {

            // Log a message and exit. Never ignore interrupted exception.
            break;
        }
    }
}

Or something like that.

或类似的东西。

#4


Note that a Timer (or similar) would be better in that you could at least reuse it and let it do with all of the details of sleeping, scheduling, exception handling, etc...

请注意,Timer(或类似的)会更好,因为你至少可以重复使用它,并让它完成睡眠,调度,异常处理等所有细节......

There are many reasons your app could die. Don't focus on just the one.

您的应用可能会死的原因有很多。不要只关注那一个。

If it's even theoretically possible for your JDBC work to leave things in a half-correct state, then you have a bug you should fix. All of your DB work should be in a transaction. It should go or not go.

如果理论上你的JDBC工作甚至可以将事物保持在半正确状态,那么你就应该修复一个bug。您的所有数据库工作都应该在事务中。应该去还是不去。

#5


This is Java. Move your processing to a second thread. Now you can

这是Java。将处理移至第二个线程。现在你可以

  • Read from stdin in a loop. If someone types "QUIT", set the while flag to false and exit.
  • 从循环中的stdin读取。如果有人键入“QUIT”,请将while标志设置为false并退出。

  • Create a AWT or Swing frame with a STOP button.
  • 使用STOP按钮创建AWT或Swing框架。

  • Pretend you are a Unix daemon and create a server socket. Wait for someone to open the socket and send "QUIT". (This has the added bonus that you can change the sleep to a select with timeout.)
  • 假装您是一个Unix守护进程并创建一个服务器套接字。等待有人打开插座并发送“退出”。 (这有额外的好处,您可以将睡眠更改为超时选择。)

There must be hundreds of variants on this.

必须有数百个变种。

#6


Set up a signal handler for SIGTERM that sets a flag telling your loop to exit its next time through.

为SIGTERM设置一个信号处理程序,设置一个标志告诉你的循环下一次退出。

#7


Regarding the question "The program could be in the middle of a JDBC call. How could I go about terminating it more gracefully?" - see How can I abort a running jdbc transaction?

关于“程序可能正在进行JDBC调用的问题。我怎样才能更优雅地终止它?” - 请参阅如何中止正在运行的jdbc事务?

Note that using a poll with sleep() is rarely the correct solution - implemented improperly, it can end up hogging CPU resources (the JVM thread-scheduler ends up spending inordinate amount of time sleeping and waking up the thread).

请注意,使用带有sleep()的轮询很少是正确的解决方案 - 实现不当,最终会占用CPU资源(JVM线程调度程序最终会花费大量时间来休眠和唤醒线程)。

#8


I‘ve created a Service class in my current company’s utility library for these kinds of problems:

我在当前公司的实用程序库中为这些问题创建了一个Service类:

public class Service implements Runnable {

    private boolean shouldStop = false;

    public synchronized stop() {
        shouldStop = true;
        notify();
    }

    private synchronized shouldStop() {
        return shouldStop;
    }

    public void run() {
        setUp();
        while (!shouldStop()) {
            doStuff();
            sleep(60 * 1000);
        }
    }

    private synchronized sleep(long delay) {
        try {
            wait(delay);
        } catch (InterruptedException ie1) {
            /* ignore. */
        }
    }

}

Of course this is far from complete but you should get the gist. This will enable you to simply call the stop() method when you want the program to stop and it will exit cleanly.

当然,这远非完整,但你应该得到要点。这样您就可以在希望程序停止时简单地调用stop()方法,它将干净地退出。

#9


If that's your application and you can modify it, you can:

如果这是您的应用程序并且您可以修改它,您可以:

  • Make it read a file
  • 让它读取文件

  • Read for the value of a flag.
  • 读取标志的值。

  • When you want to kill it, you just modify the file and the application will exit gracefully.
  • 当你想杀死它时,你只需修改文件,应用程序就会正常退出。

Not need to work it that harder that that.

不需要那样努力工作。

#10


You could make the field a compound value that includes (conceptually) a process-ID and a timestamp. [Better yet, use two or more fields.] Start a thread in the process that owns access to the field, and have it loop, sleeping and updating the timestamp. Then a polling process that is waiting to own access to the field can observe that the timestamp has not updated in some time T (which is much greater than the time of the updating loop's sleep interval) and assume that the previously-owning process has died.

您可以将该字段设置为包含(概念上)进程ID和时间戳的复合值。 [更好的是,使用两个或更多字段。]在拥有对字段的访问权限的进程中启动一个线程,并使其循环,休眠和更新时间戳。然后,等待访问该字段的轮询进程可以观察到时间戳在某个时间T内没有更新(这比更新循环的休眠间隔的时间长得多)并且假设先前拥有的进程已经死亡。

But this is still prone to failure.

但这仍然容易失败。

In other languages, I always try to use flock() calls to synchronize on a file. Not sure what the Java equivalent is. Get real concurrency if you at all possibly can.

在其他语言中,我总是尝试使用flock()调用来同步文件。不确定Java等价物是什么。如果你可能的话,获得真正的并发。

#11


I'm surprised nobody mentioned the interrupt mechanism implemented in Java. It's supposed to be a solution to the problem of stopping a thread. All other solutions have at least one flaw, that's why this mechanism is needed to be implemented in the Java concurrency library.

我很惊讶没人提到Java中实现的中断机制。它应该是解决线程停止问题的解决方案。所有其他解决方案至少有一个缺陷,这就是为什么需要在Java并发库中实现此机制的原因。

You can stop a thread by sending it an interrupt() message, but there are others ways that threads get interrupted. When this happens an InterruptedException is thrown. That's why you have to handle it when calling sleep() for example. That's where you can do cleanup and end gracefully, like closing the database connection.

您可以通过向线程发送一条中断()消息来停止线程,但还有其他方法可以使线程中断。发生这种情况时,会抛出InterruptedException。这就是为什么你在调用sleep()时必须处理它的原因。这就是你可以进行清理并优雅地结束的地方,比如关闭数据库连接。

#12


Java9 has another "potential" answer to this: Thread.onSpinWait():

Java9有另一个“潜在的”答案:Thread.onSpinWait():

Indicates that the caller is momentarily unable to progress, until the occurrence of one or more actions on the part of other activities. By invoking this method within each iteration of a spin-wait loop construct, the calling thread indicates to the runtime that it is busy-waiting. The runtime may take action to improve the performance of invoking spin-wait loop constructions.

表示调用者暂时无法进展,直到其他活动发生一个或多个操作为止。通过在自旋等待循环结构的每次迭代中调用此方法,调用线程向运行时指示它正在忙等待。运行时可以采取措施来提高调用自旋等待循环结构的性能。

See JEP 285 for more details.

有关详细信息,请参阅JEP 285。

#13


I think you should poll it with timertask instead.

我认为你应该用timertask轮询它。

My computer is running a while loop 1075566 times in 10 seconds. Thats 107557 times in one second.

我的电脑在10秒内运行了1075566次循环。这是一秒钟107557次。

How often is it truly needed to poll it? A TimerTask runs at its fastest 1000 times in 1 second. You give it a parameter in int (miliseconds) as parameters. If you are content with that - that means you strain your cpu 108 times less with that task.

轮询真正需要多长时间? TimerTask以1秒的最快速度运行1000次。你给它一个int(miliseconds)参数作为参数。如果您对此感到满意 - 这意味着您可以使用该任务减少108倍的CPU压力。

If you would be happy with polling once each second that is (108 * 1000). 108 000 times less straining. That also mean that you could check 108 000 values with the same cpu strain that you had with your one while loop - beause the you dont assign your cpu to check as often. Remember the cpu has a clock cycle. Mine is 3 600 000 000 hertz (cycles per second).

如果您对每秒的轮询(108 * 1000)感到满意。紧张减少108000倍。这也意味着你可以检查108000个值与你的while循环相同的cpu应变 - 因为你不经常分配你的cpu进行检查。记住cpu有一个时钟周期。我的是3 600 000 000赫兹(每秒周期数)。

If your goal is to have it updated for a user - you can run a check each time the user logs in (or manually let him ask for an update) - that would practically not strain the cpu whatsoever.

如果您的目标是为用户更新它 - 您可以在每次用户登录时运行检查(或手动让他请求更新) - 这实际上不会给cpu带来任何压力。

You can also use thread.sleep(miliseconds); to lower the strain of your polling thread (as it wont be polling as often) you where doing.

你也可以使用thread.sleep(miliseconds);降低轮询线程的压力(因为它不经常轮询)你在哪里做。