开发者

Synchronized Methods in Java

开发者 https://www.devze.com 2023-04-01 16:36 出处:网络
Just wanted to check to make sure that I understand this.A synchronized method doesn\'开发者_Go百科t create a thread, right?It only makes sure that no other thread is invoking this method while one th

Just wanted to check to make sure that I understand this. A synchronized method doesn'开发者_Go百科t create a thread, right? It only makes sure that no other thread is invoking this method while one thread within the same process (ie the JVM) is using it, right?


A synchronized method doesn't create a thread, right?

Right.

It only makes sure that no other thread is invoking this method while one thread within the same process (ie the JVM) is using it, right?

Right.

For more information, read Synchronized Methods. I also recommend reading Java Concurrency in Practice.


That's mostly correct. Calling a synchronized method does not spawn a new thread. It just makes other threads block when they try to call any other synchronized method for that instance of that object.

The key thing to remember is that all synchronized methods of a class use the same lock.


Yes.

There is another important role for synchronized blocks too: when a thread enters a synchronized block it sees the changes to the values made by the previous thread that accessed that block (or another block synchronized with the same lock).

Basically on a multicore cpu, each thread as its own memory cache on its core: each core has copies of the same variables, their values might be different on each core. When there is a synchronized operation, the JVM makes sure that the variable values are copied from one memory cache to the other. A thread entering a synchronzed block then sees the values "updated" by a previous thread.

As suggested by mre, Java Concurrency in Practice is a good reference if you really want to understand multithreading and learn best practices.

0

精彩评论

暂无评论...
验证码 换一张
取 消