The_dempa
The_dempa

Reputation: 115

How to use a Thread to check every time (like running it in background) until my condition is true

I have this code sample. But everytime I run it, It won't wait until my condition is true I need this Thread to be like something that continuously looking until the condition is true.

My condition is: sum.contains(jLabel11.getText())

I need the Thread to work until this condition becomes true. Using a while(true) statement do this thing, but sometime it will be a bad condition for the program because it will keep printing and printing thousands of lines (in my case: "Not equal yet") until the condition inside if statement is true

But I really need this Thread to look over and over (continuously) until my condition in if statement is true without printing the statement in else condition thousand times or without printing the statement in if condition thousand times even after my condition inside if statement is true. But I need to print the statement inside if statement only one time to know that my condition became true

new Thread() {
                public void run() {
                    try {
                        Thread.sleep(100);
                        if (sum.contains(jLabel11.getText())) {
                            System.out.println("Now equal");
                        } else {
                            System.out.println("Not equal yet");
                        }
                    } catch (InterruptedException ex) {
                        Logger.getLogger(AlarmClock.class.getName()).log(Level.SEVERE, null, ex);
                    }

                }

            }.start();

Upvotes: 2

Views: 1598

Answers (3)

Marco Vargas
Marco Vargas

Reputation: 1327

The solution seems simple, just add the while(true) and if it goes inside the condition breaks the execution to go out the while and out the thread, something like this:

new Thread() {
    public void run() {
        try {
            while (true){
                if (sum.contains(jLabel11.getText())) {
                    System.out.println("Now equal");
                    break;
                }
            }
        } catch (InterruptedException ex) {
            Logger.getLogger(AlarmClock.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}.start();

Now, as explained in other answers, this is called a selfish thread which tend to demand more resources than a monitor or other event-like patterns.

On new Architectures (SMP = Symmetric Multi processor) selfish threads are not an issue... but there are some architectures where it can be really a problem (such MPP Massive Parallel Processor architectures)

Now, regarding the statement you stated:

It won't wait until my condition is true I

It seems your main thread is reaching its end before this new Thread you are creating...

For example, if you have that code in an Unit Test (JUnit), you have to put a thread.sleep to wait until the condition is fulfill, or Mock sum.contains(jLabel11.getText()) to unit test it...

If not, the main thread will finish and all its child threads will be terminated with it.

Upvotes: 1

Mark Adelsberger
Mark Adelsberger

Reputation: 45659

While you could do as Rogue suggests, it's almost always a terrible idea. It wastes a lot of computing power on having a thread "spin" (i.e. sit in a loop continuously testing a condition). It also does not offer a particularly good guarantee of the thread noticing "right away" (or within any given time frame) when the condition becomes true. (You would need a real-time threading system to provide that kind of guarantee.)

You'll get at least as good a responsiveness, and without unnecessarily occupying a processor, using monitors. In java every object is potentially a monitor. Check out the JavaDoc for notify and wait as a good starting point.

So a simple pattern that mght work: you create a monitor, your background thread waits on that monitor, and any operation that could affect the condition to be tested calls notify on the monitor. Your thread, when awoken, checks the condition and either does its work or goes back to sleep (by again waiting), accordingly.

Upvotes: 1

SF23
SF23

Reputation: 184

Then do it like this:

   while(!(sum.contains(jLabel11.getText())){
Thread.yield();
}
System.out.println("Now equal");

Upvotes: -1

Related Questions