有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在java主程序的后台实现事件侦听器?

嗨,我是一个初学者,很抱歉我的问题听起来很幼稚

我想实现一个在后台运行并一直监听的线程。通过监听,我的意思是,假设它不断检查从主线程返回的值,如果vaue超过某个数字,它就会执行某个方法,或者说退出程序

如果你能给我一些想法,或者至少给我介绍一些有用的东西,那就太好了


共 (4) 个答案

  1. # 1 楼答案

    我想你可以简单地为主线程使用gui组件,比如JTextField, 然后阅读事件处理,您将很容易听到文本字段输入值的状态变化

  2. # 2 楼答案

    如果您只是需要轮询另一个线程的结果,请尝试使用@Piotr建议的java.util.concurrent包。下面是一个具体的例子,你可以这样做:

    import java.util.concurrent.*;
    
    class Main{
        public static void main(String[] args) throws Exception{
            //Create a service for executing tasks in a separate thread
            ExecutorService ex = Executors.newSingleThreadExecutor();
            //Submit a task with Integer return value to the service
            Future<Integer> otherThread = ex.submit(new Callable<Integer>(){
                public Integer call(){
                    //do you main logic here
                    return 999;//return the desired result
                }
            }
    
            //you can do other stuff here (the main thread)
            //independently of the main logic (in a separate thread)
    
            //This will poll for the result from the main
            //logic and put it into "result" when it's available
            Integer result = otherTread.get();
    
            //whatever you wanna do with your result
        }
    }
    

    希望这有帮助

  3. # 4 楼答案

    您不希望该线程在循环中运行,不断轮询值,因为这会浪费处理

    理想情况下,当值发生变化时,会主动通知侦听器。这将要求任何修改监视值的代码调用一个特殊方法。侦听器可能不需要在单独的线程中运行;这将取决于听者在收到通知时做了什么

    如果无法更改修改该值的代码,那么最好是每隔一段时间检查该值。您不会立即看到更改,而且可能会完全错过更改,因为该值在一个时间间隔内多次更改

    以下哪种解决方案最适合您的情况