multithreading - How to synchronize a static variable among threads running different instances of a class in java? -


I know that using a synchronized keyword before any method brings synchronization to that object.
That is, the same instance of the object running 2 threads will be synchronized.
However, synchronization is at the object level, since 2 threads running different examples of objects will not be synchronized. Therefore, if we have a fixed variable in the Java class that is called by law, then we want to synchronize it in all instances of the class.
Two examples are running in two different threads.
What can we do to get the synchronization in the following manner?

 Public Class Test {Personal Static Int Calculation = 0; Private fixed final object lock = new object (); Public synchronized void foo () {synchronize (lock) {count ++; }}} 

Is it true that since we have define an object 'lock' which is stable and we are using synchronized keywords for that lock, now the static variable count class Is all the examples of the test being synchronized?

There are several ways to synchronize access to fixed variables.

  1. Use a synchronized static method it synchronizes on the class object.

      public class test {Private static calculation = 0; Public stable synchronization zero increase salary () {count ++; }}  
  2. Clearly synchronize on a class object.

      public class test {Private static calculation = 0; Public Zero Enhance (Calculation) {Synchronize (Test Class) {count ++; }}}  
  3. Synchronize on some other stationary objects.

      public class test {personal fixed int count = 0; Private static final item countLock = new object (); Public Zero Enhancement Salary (CountLock) {count ++; Method} 3 is best in many cases because the lock object is not exposed outside your class. 


Comments

Popular posts from this blog

oracle - The fastest way to check if some records in a database table? -

php - multilevel menu with multilevel array -

jQuery UI: Datepicker month format -