I have two methods in which I want to be able to run concurrently.
public void bar(){
//Do some stuff which has a result
//If result is true, then stop foo().
}
public void foo()
{
for (int x = 0; x <= 100; ++x)
{
//Do some stuff...
//Execute bar, but don't wait for it to finish before jumping to next iteration.
}
}
The way I understand it, when a method is called, it gets put onto the stack, and then when the method finishes it returns from the stack and then the program will continue to execute from where the method was called.
So if foo() calls bar() during the loop it will wait until bar() returns before continuing the loop.
However, what I want to happen is that when foo executes bar, it doesn't wait until bar has finished executing before it continues its iteration; it just notifies that bar() should run and then continues looping.
Similar to how run
in a Thread will run the method and then return it, but start
will start the run
method in a new thread, and the start
method returns immediately, allowing the next line of code to run.
Additionally, each time bar() is run, depending on the result, I want it to interrupt foo() regardless of which line of foo() is currently being executed. I do not want to check the result of bar() within the foo() method, but I want functionality such that while foo() is executing it is interrupted by bar()'s execution.
Hopefully, to make this simpler to understand: let's say I have two people doing tasks A and B. A is foo, and B is bar.
A is going to do his task 100 times, but after each time he does a task he tells B to do his respective task (calling bar() at the end of each iteration), and then continues onto the next of his tasks.
The time it takes B to do his task is shorter than the time it takes A to do his task, so when B finishes his task, A will still be executing his task, and depending on the result of B's task, he may tell A to halt the execution of his task.