Home > Net >  Java Multithreading - how to use wait() and notify() to get a value from only 1 thread out of 2 and
Java Multithreading - how to use wait() and notify() to get a value from only 1 thread out of 2 and

Time:12-02

In my main thread I create two additional threads that I want to use a value from. Basically what I want to do is this:

Threads thread1 = new Threads();
Threads thread2 = new Threads();
Thread.currentThread.wait();
If (thread1 = complete){
var = thread1.getter
//delete thread2
}
If (thread2 == complete){
var = thread2.getter
//delete thread1
}

With thread1 and thread2 having a notify() at the end that wakes up the main thread and the thread that doesn't finish is deleted. But I realise that I don't properly understand wait() and multithreading so the way this is setup may not be correct. I know that Thread.currentThread.wait() is definitely not correct.

I think I may have to synchronize the methods but I have not been able to find any examples that show how to do this in this situation.

Edit: To give more info Thread1 takes input from a scanner and Thread2 takes input from a keylistener and I want to use the first input from 1 of them

CodePudding user response:

I think you are saying that your threads are racing to solve a problem, and you are only interested in whichever solution is produced first. Am I right? If so, then what you need is some shared variables that allow all the threads to know if a solution has been found:

boolean solution_is_found = false;
SolutionType solution;
final Object solution_mutex = new Object();

A worker thread can do this:

while (true) {
    synchronized(solution_mutex) {
        if (solution_is_found) {
            // Some other thread won the race, our solution is not needed.
            return;
        }
    }
    ...do some increment of work...
    if (...this thread found a solution...) {
        synchronized(solution_mutex) {
            if (! solution_was_found) {
                // Only update the variables if this thread won the race.
                solution_is_found = true;
                solution = ...what this thread found...
                solution_mutex.notifyAll();
            }
        }
        return;
    }
}

And now, the main thread can await the appearance of the first solution.

synchronized(solution_lock) {
    while (! solution_was_found) {
        solution_lock.wait();
    }
}

...use `solution` here...

If the smallest possible "increment of work" takes a significant chunk of time, then you may want to test solution_is_found several times within the "increment," and abort if it is true.

CodePudding user response:

You don't need wait and notify in your case. Just use join to wait until the thread is completed.

More info: Java Wait for thread to finish

  • Related