How to implement an event listener in the background of the main program in java?

Hi, newbie, so sorry for my question if that sounds naive.

I want to implement a thread that runs in the background and is constantly listening. Listening to what I mean, let's say it continues to check the value returned from the main thread, and if the vaue value exceeds a certain digit, it executes some method or says it quits the program.

If you could give me some idea or at least refer to something useful, that would be great.

+5
source share
5 answers

You do not want this thread to run in a loop, continuously checking the value, because it could recycle the waste treatment.

, . , , , . , , ; , , .

, , , , , . , , , .

?

+2

Java ( concurrency Java, ). ( , ).

+1

, java.util.concurrent, @Piotr. , :

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 available
        Integer result = otherTread.get();

        //whatever you wanna do with your result
    }
}

, .

+1

, gui , JTextField, , .

0
0
source

All Articles