术语同步和线程安全是什么意思? [英] What do the terms synchronized and thread-safe mean?

查看:42
本文介绍了术语同步和线程安全是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看了很多关于数据结构的视频,这些术语总是被提及:synchronized/not synchronizedthread-safe/not thread-safe.

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.

谁能用简单的话向我解释一下 Java 中 synchronizedthread-safe 的含义?什么是sync,什么是thread?

Can someone explain to me in simple words what synchronized and thread-safe mean in Java? What is sync and what is thread?

推荐答案

thread 是程序的执行路径.单线程程序只有一个thread,所以不会出现这个问题.几乎所有的 GUI 程序都有多个执行路径,因此有多个线程——一个用于处理 GUI 的显示和处理用户输入,另一个用于实际执行程序的操作.这是为了在程序运行时 UI 仍然可以响应.

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.

用最简单的术语来说,threadsafe 意味着从多个线程访问是安全的.当您在程序中使用多个线程并且它们每个都试图访问内存中的公共数据结构或位置时,可能会发生一些不好的事情.所以,你添加了一些额外的代码来防止那些不好的事情.例如,如果两个人同时编写同一个文档,则第二个人保存将覆盖第一个人的工作.为了确保线程安全,您必须强制第 1 个人等待第 2 个人完成他们的任务,然后再允许第 1 个人编辑文档.

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 意味着在多线程环境中,Synchronized 对象不会让两个线程同时访问一个方法/代码块.这意味着一个线程无法读取,而另一个线程更新它.

Synchronized means that in a multiple threaded environment, a Synchronizedobject 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.

如果您的应用程序是单线程的,Synchronized 没有任何好处.

If your application is single threaded though, Synchronized has no benefit.

这篇关于术语同步和线程安全是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆