Breaking the four of Java myth: synchronous code is equivalent to cross-section (critical section)

xiaoxiao2021-03-06  89

Synchronization is often quoted as a section. The section refers to only one thread to execute it at a time. Multiple threads are possible to perform synchronization code simultaneously. This misunderstanding is because many programmers believe that the sync key is locked in the code it surrounded. But the actual situation is not like this. Synchronous lock is an object, not code. Therefore, if there is a synchronization method in your class, this method can be executed simultaneously by two different threads, as long as each thread creates an instance of such a class. Refer to the following code: Class foo extends thread {private int val; public foo (int V) {val = v;} public synchronized void printval (int V) {while (true) system.out.println (v);} public Void Run () {PrintVal (VAL);}} class synctest {public static void main (string args []) {few f1 = new foo (1); f1.start (); f2 = new foo (3); F2.Start ();}} The output generated by running SyncTest is 1 and 3 intersection. If PrintVal is a section, the output you see can only be 1 or can only be 3 without being both simultaneous. The results of the program run prove that the two threads perform the Printval method even if the method is synchronized and is not terminated due to an infinite loop. To achieve a real section, you must synchronize a global object or synchronize classes. The following code gives a such example. Class Foo Extends Thread {Private Int Val; Public Foo (INT V) {VAL = V; PUBLIC VOID PRINTVAL (INT V) {SYNCHRONIZED (FOO.CLASS) {While (true) system.out.println (v);} } Public void Run () {printVal (VAL);}} The above class is no longer synchronized for individual class instances but synchronization. For class foo, it only has unique class definitions, and two threads are synchronized in the same lock, so there is only one thread to execute the PrintVal method. This code can also be locked by the public object. For example, add a static member to FOO. Both methods can synchronize this object to achieve thread security. Translator Note: The following author gives a reference implementation, gives two usual methods for synchronous public objects: 1, class foo extends thread {private int valiVate static object lock = new object (); public foo (int V) {VAL = v;} public void printval (int V) {while (true) system.out.println (v);}} public void run () {printval (val);}} Examples are better than the example given in the original text, because the chain in the original text is defined for class, one class can only have a class definition, and the synchronous general principle is to minimize the granularity of synchronization to reach better performance. . The synchronization granularity given by the author is smaller than the original.

转载请注明原文地址:https://www.9cbs.com/read-125034.html

New Post(0)