Java – How to make two threads interact with each other without stopping the execution of the thread

javamultithreading

This might sound similar to some of the other questions but it does not deal with wait or notify.

I have two threads which do two different things
The first forms a process in the background and changes behavior when it receives an input from the other thread that interacts with the user.

Best Answer

There's a simple way to do this: You set up an object with the synchronized data and share it between the threads. You can then write the data or check for it from each thread.

So, you'd have an instance of a class that looks like this:

public class Shared {
    private boolean signalSent = false;

    public synchronized boolean isSignalSent(){
        return this.signalSent;
    }

    public synchronized void setSignalSent(boolean signal){
       this.signalSent = signal;  
    }
}

You may want to consider, if the signal can be re-sent, to have a method that reads and resets the value.

In any case, the instance of that class should be passed to both threads, and will be able to do something like

if(!shared.isSignalSent()){
    // behave a certain way
} else {
    // behave another way
}
Related Topic