术语同步和线程安全是什么意思?
What do the terms synchronized and thread-safe mean?
我看了很多关于数据结构的视频,总是提到这些术语:synchronized/not synchronized
和thread-safe/not thread-safe
。
有人可以用简单的语言向我解释 synchronized
和 thread-safe
在 Java 中的意思吗? sync
是什么,thread
是什么?
一个thread
是一个程序的执行路径。单线程程序只有一个thread
,所以不会出现这个问题。实际上,所有 GUI 程序都有多个执行路径,因此有多个线程 - 一个用于处理 GUI 的显示和处理用户输入,其他用于实际执行程序的操作。这样 UI 在程序运行时仍然可以响应。
用最简单的术语来说threadsafe
意味着从多线程访问是安全的。当您在程序中使用多个线程并且它们每个都试图访问内存中的公共数据结构或位置时,可能会发生一些不好的事情。所以,你添加一些额外的代码来防止那些不好的事情。例如,如果两个人同时编写同一份文档,则第二个保存的人将覆盖第一个人的工作。为了使其成为线程安全的,您必须强制第 1 个人等待第 2 个人完成他们的任务,然后才允许第 1 个人编辑文档。
Synchronized
表示在多线程环境下,一个Synchronized
对象不会让两个线程同时访问一个method/block的代码。这意味着一个线程无法在另一个线程更新它的同时读取它。
第二个线程将等到第一个线程完成。开销是速度,优点是保证数据的一致性。
如果您的应用程序是单线程的,Synchronized
没有任何好处。
根据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.
因此,线程安全是程序在被多个线程访问时所期望的行为。使用 synchronized
块是实现该行为的一种方法。您还可以检查以下内容:
What does 'synchronized' mean?
What does threadsafe mean?
我看了很多关于数据结构的视频,总是提到这些术语:synchronized/not synchronized
和thread-safe/not thread-safe
。
有人可以用简单的语言向我解释 synchronized
和 thread-safe
在 Java 中的意思吗? sync
是什么,thread
是什么?
一个thread
是一个程序的执行路径。单线程程序只有一个thread
,所以不会出现这个问题。实际上,所有 GUI 程序都有多个执行路径,因此有多个线程 - 一个用于处理 GUI 的显示和处理用户输入,其他用于实际执行程序的操作。这样 UI 在程序运行时仍然可以响应。
用最简单的术语来说threadsafe
意味着从多线程访问是安全的。当您在程序中使用多个线程并且它们每个都试图访问内存中的公共数据结构或位置时,可能会发生一些不好的事情。所以,你添加一些额外的代码来防止那些不好的事情。例如,如果两个人同时编写同一份文档,则第二个保存的人将覆盖第一个人的工作。为了使其成为线程安全的,您必须强制第 1 个人等待第 2 个人完成他们的任务,然后才允许第 1 个人编辑文档。
Synchronized
表示在多线程环境下,一个Synchronized
对象不会让两个线程同时访问一个method/block的代码。这意味着一个线程无法在另一个线程更新它的同时读取它。
第二个线程将等到第一个线程完成。开销是速度,优点是保证数据的一致性。
如果您的应用程序是单线程的,Synchronized
没有任何好处。
根据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.
因此,线程安全是程序在被多个线程访问时所期望的行为。使用 synchronized
块是实现该行为的一种方法。您还可以检查以下内容:
What does 'synchronized' mean?
What does threadsafe mean?