Hi im a beginner so sorry for my question if it sounds naive.
I want to implement a thread that runs in the background and listens all the time. By listening i mean, say it keeps check on a value returned from main thread and if the vaue exceeds certain figure, it executes some method, or say exits the program.
If you could give me some idea or at least refer me to something useful, that'll be great.
You wouldn't want this thread to run in a loop, continuously polling the value, because that would waste processing.
Ideally, the listener would be actively notified when the value had changed. This would require that any code that modifies the monitored value call a special method. It might not be necessary for the listener to run in a separate thread; it would depend on what the listener does when it is notified.
If the code that modifies the value cannot be changed, then the best you can do is to check the value at intervals. You won't see a change immediately, and its possible that you could miss changes altogether because the value is changing multiple times during an interval.
Which of these solutions fits your situation the best?
You can find some information on using threads in Java Tutorials (if you are new to concurrency in Java I recommend reading this tutorial first). Especially this section may be useful for you (it shows how to create and start a new thread).
If you simply need to poll for a result from another thread try using java.util.concurrent
package as suggested by @Piotr. Here's a concrete example how you might do this:
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
}
}
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With