Detailed example of synchronize function in Java

Detailed example of synchronize function in Java

If the member function of a class in Java is decorated with synchronized, it corresponds to the same object. When multiple threads call the synchronization function of this object, they must wait until the previous thread is called before being called by the next thread.

If two member functions of a class are modified by synchronized, as shown in the code, can one call funca and the other call funcb for the same object when two threads are running?

Mysyn is such a class. If I have two threads, one runs funca and then funcb in the run method, and the other runs funcb and then funca in the run method. Is it possible that start a Directly output start B?

The test code is as follows:

This thread runs funca first

This thread runs funcb first

Most of the output results are:

If you cancel the sleep between two function calls in the run method of myThread, the results are:

Personal results may vary according to thread scheduling, but there will never be: start a Then directly output start b

If funcb is not a synchronization function, what will be the result of the above code?

The code is slightly changed to remove the synchronized keyword of funcb. The operation result is:

Obviously, start a appears Then directly output start b Results.

Similarly, if the mysyn class has a public member variable, the multithread can also modify the member variable by another thread while the resynchronization function is called.

The above experiments show that synchronous member functions can only have exclusive effects on other synchronous functions (including themselves) in the synchronous function call of the same object, that is, in multi-threaded operation, the same object can only have one synchronous function running at present, but it does not exclude the operation of other asynchronous functions or access to members.

Now suppose that a class has two static synchronization methods. What about that?

I won't repeat the specific implementation, because the results are similar:

In multithreading, only one class synchronization function (static synchronization function) can be running in the same class, but it does not exclude the operation of other asynchronous static functions or access to static members

If you have any questions, please leave a message or go to the community of this site for exchange and discussion. Thank you for reading. I hope it can help you. Thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>