Learning Java, use of synchronized keyword

前端 未结 2 843
既然无缘
既然无缘 2020-12-03 06:45

so i was testing with synchronized keyword. Here is an example that I tried:

public class MyTest {
    static int i = 0;
    public static voi         


        
相关标签:
2条回答
  • 2020-12-03 07:25

    Two things:

    First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

    Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.

    Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods. (An important exception: final fields, which cannot be modified after the object is constructed, can be safely read through non-synchronized methods, once the object is constructed).

    source: http://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html

    0 讨论(0)
  • 2020-12-03 07:32

    Vulkanino gave a good answer to your main question, so I'll only address your question about 3 printing after 7.

    The 3 can print after the 7 because there is actually a lot more byte code in your statements than Java code.

    I'll expand on that.

    You call

    System.out.println("Current Counter is: " + i);
    

    and it occurs in one line of Java code, but really what happens is a string is created and then that string is passed to println. The println method itself has to do a bit of processing before it actually writes the line to the console.

    Conceptually, something like the following is happening.

    String printlnString = "Current Counter is: 3"
    --> maybe the other thread executes here
    System.out.println(printlnString);
    --> or maybe the other thread executes here
    i is now equal to 7 and the console has "Current Counter is: 7"
    println writes "Current Counter is: 3" to console
    
    0 讨论(0)
提交回复
热议问题