Create a static member with the goal of the / wait java condition

Is it possible to create a static member in a class that will respond (if its wait method is called), correctly for threads that do not use the same instance of the class (could they notify each other notifyAll using a static member field)?

+4
source share
1 answer

You can save one instance in a static field of the class, in which any number of threads can wait on. If the instance is stored, it does not matter. The key is that all threads have access to a single instance - whether from a static field / method or from a single service object or a static local variable.

 public class MakeMeWait { private static Object semaphore = new Object(); public static void waitPlease() { semaphore.wait(); } public static void wakePlease() { semaphore.notifyAll(); } } 

This example uses the built-in Java methods wait and notifyAll , you are much better off using java.util.concurrent instead of rolling your own multi-threaded solutions.

+4
source

Source: https://habr.com/ru/post/1402170/


All Articles