Stop the code until the condition is met

How can you create a function or component, etc., that will stop all current code until the condition is met?

For example, the same as JOptionPane, if I have this, for example:

JOptionPane.showInputDialog(null, "Hello", "Title", 1); 

Inside the function, etc., and then after that print to the console, it will not print until I close JOptionPane.

I suppose this component has some kind of stream setting built in for this, but how can I duplicate this with my own functions?

So say, for example, I wanted JFrames to delay everything until it was closed, so it acts like a JOptionPane.

Or, for example, there is a function that had several inputs that were updated, and inside it some mathematical calculations were performed with them, and if it were a certain value, the returned logical value, but then everything else, but they were suspended until then until the true boolean returns.

I suppose the solution is some kind of thread setup, but I'm pretty new to Java, and when I encoded in the past, I really didn't use streams, so I can't create a good system stop-start / pause-run style function yet .

Does anyone have any suggestions on how to achieve this or better, but code examples showing how this type works?

+4
source share
2 answers

You create a monitor (which is just plain Object )

 public static final Object monitor = new Object(); public static boolean monitorState = false; 

Now you create a wait method

 public static void waitForThread() { monitorState = true; while (monitorState) { synchronized (monitor) { try { monitor.wait(); // wait until notified } catch (Exception e) {} } } } 

and a method to unlock your waiters.

 public static void unlockWaiter() { synchronized (monitor) { monitorState = false; monitor.notifyAll(); // unlock again } } 

So, when you want to do something fantastic, you can do it like this:

 new Thread(new Runnable() { @Override public void run() { // do your fancy calculations unlockWaiter(); } }).start(); // do some stuff waitForThread(); // do some stuff that is dependent on the results of the thread 

Of course, there are many possibilities, this is only one version of how to do this.

+7
source

Have you tried a sleeping stream?

as simple as Thread.sleep(timeInMilliseconds)

check here

+1
source

All Articles