You must write 2 threads. Flow A with a periodicity of 10 seconds will switch from the “allowed” state to the “not allowed” state, and 2 threads that will wait for the status of the Flow A “allowed” and start counting from 10, and stop their action as soon as the state of the flow A changes to not allowed state. How best to do this. I thought that in the flow A to introduce a variable value of which will change. But how can I then determine the current value of the variable A in stream B? Advise in which direction to dig or how best to do it. Thank you in advance. Flow Code A:

class A extends Thread{ public boolean isAllowed=false; A(){ } public void run(){ for(int i=0; i<10; i++){ try { Thread.sleep(10000); isAllowed=true; } catch (InterruptedException e) { System.err.println(e); } } } } 
  • Try using callbacks. You pass a callback from class B to class A , and when you consider that the state is “allowed”, in class A pull the callback, and in class B already perform the necessary actions. - Peter Samokhin
  • Read about mutexes, semaphores, and similar synchronization primitives. - VladD

1 answer 1

You can use, for example, the shared variable AtomicBoolean , or read about semaphores and mutexes (there is a huge topic, there are many high-level classes in Java for working with multithreading):

 class A extends Thread{ private final AtomicBoolean isAllowed; A(AtomicBoolean isAllowed){ this.isAllowed = isAllowed; } public void run(){ for(int i=0; i<10; i++){ try { Thread.sleep(10000); isAllowed.set(i % 2); } catch (InterruptedException e) { System.err.println(e); } } } } class B extends Thread{ private final AtomicBoolean isAllowed; B(AtomicBoolean isAllowed){ this.isAllowed = isAllowed; } public void run(){ if(isAllowed.get()) { ... } } }