2010-12-23 315 views
5

嗨,我是初学者,所以很抱歉我的问题,如果它听起来天真。如何在java的主程序的后台实现事件监听器?

我想实现一个在后台运行并且一直监听的线程。通过监听我的意思,说它保持检查从主线程返回的值,如果该值超过某个数字,它执行一些方法,或说退出程序。

如果你能给我一些想法或者至少把我介绍给一些有用的东西,那会很棒。

回答

2

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

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

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

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

+0

谢谢你的回答。我正在考虑最初实施循环。其实我正在通过Windows命令行执行一个外部进程,并且作为回报,我读取了一个我需要跟踪的值。我以字符串格式获得响应,并将其转换回int以应用检查。 我想通过循环中的Runtime.getRuntime()。exec()继续调用这个外部进程,并每隔2秒定期检查一次该值。它毫不敏感地以毫秒为单位。你认为这样做是一个明智的想法吗? – 2010-12-23 01:20:48

+0

@Sara - 你的计划听起来像是一个适当的方式来处理它。我建议查看[`ScheduledExecutorService`](http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ScheduledExecutorService.html)创建一个线程,该线程将运行此检查固定的时间间隔。 – erickson 2010-12-23 05:30:44

+0

[This StackOverflow question](http://stackoverflow.com/questions/426758/running-a-java-thread-in-intervals)和接受的答案提供了一个如何使用`ScheduledExecutorService`的好例子。 – erickson 2010-12-23 05:33:33

1

你可以在Java Tutorials中找到关于使用线程的一些信息(如果你对Java的并发性不熟悉,我建议先阅读本教程)。尤其是this section可能对你有用(它显示了如何创建和启动一个新线程)。

0

我想你可以简单地使用一个GUI组件像一个JTextField主线程,然后 阅读事件处理,你将能够轻松地听文本字段输入值的状态变化。

1

如果您只是需要根据另一个线程查询结果,请使用@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 
    } 
} 

希望这会有所帮助。