问题
I've been watching a lot of videos on data structures, and these terms are always being mentioned: synchronized/not synchronized
and thread-safe/not thread-safe
.
Can someone explain to me in simple words what synchronized
and thread-safe
mean in Java? What is sync
and what is thread
?
回答1:
A thread
is an execution path of a program. A single threaded program will only have one thread
and so this problem doesn't arise. Virtually all GUI programs have multiple execution path and hence threads - one for processing the display of the GUI and handing user input, others for actually performing the operations of the program. This is so that the UI is still responsive while the program is working.
In the simplest of terms threadsafe
means that it is safe to be accessed from multiple threads. When you are using multiple threads in a program and they are each attempting to access a common data structure or location in memory several bad things can happen. So, you add some extra code to prevent those bad things. For example, if two people were writing the same document at the same time, the second person to save will overwrite the work of the first person. To make it thread safe then, you have to force person 1 to wait for person 2 to complete their task before allowing person 1 to edit the document.
Synchronized
means that in a multiple threaded environment, a Synchronized
object does not let two threads access a method/block of code at the same time. This means that one thread can't be reading while another updates it.
The second thread will instead wait until the first is done. The overhead is speed, but the advantage is guaranteed consistency of data.
If your application is single threaded though, Synchronized
has no benefit.
回答2:
As per CIP:
A class is thread-safe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment, and with no additional synchronization or other coordination on the part of the calling code.
So thread safety is a desired behavior of the program in case it is accessed by multiple threads. Using the synchronized
block is one way of achieving that behavior. You can also check the following:
What does 'synchronized' mean?
What does threadsafe mean?
来源:https://stackoverflow.com/questions/32163445/what-do-the-terms-synchronized-and-thread-safe-mean