有人可以用外行术语解释线程安全吗?
尽管我阅读了维基百科等内容,但我仍然不太明白线程安全在编程意义上的含义。有谁能用通俗易懂的语言给出一些Java例子吗?比如什么使线程安全与线程不安全?
谢谢!
Despite me reading wikipedia and such, I still don't really understand what Thread Safety means in a programming sense. Is anyone able to give some Java examples in layman terms? Such as what makes a thread safe vs a thread unsafe?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为从计算机之外的具体事物来思考是有帮助的。 (并发编程早在数字计算机发明之前就已经完成了。)
汽车是一个过程。交叉路口是共享资源。如果多个方向的灯同时呈绿色,则可能不是线程安全的。
I think it is helpful to think in terms of concrete things outside the computer. (Concurrent programming was being done long before the invention of digital computers.)
A car is a process. An intersection is a shared resource. If the light is green in multiple directions at the same time, then it is probably not thread safe.
这是一个模糊的术语——对于它的实际含义并没有确切的一致意见。
然而,通常情况下,人们指的是可以从多个线程同时调用而不会出错的代码。
也就是说,如果代码可以同时从多个线程调用并且保证不会导致错误,则该代码被认为是线程安全的。
It is a fuzzy term - there is no exact agreement on what it actually means.
Normally, however, people mean code that can be called from multiple threads concurrently without a chance of errors.
That is - code is considered thread safe if it can be called from multiple threads at the same time and is guaranteed not to cause errors.
并不是线程安全与否。这就是保护对象状态不被多个线程更新的方式。因此,如果一次只有 1 个线程可以更新变量,那么就不会出现某种不一致或不可预测的状态,这是安全的。
线程不安全的一个示例:您有一个对象,它有一个实例变量,该变量存储一个项目列表,该对象中的 1 个方法使用该列表来保存计算结果,该计算结果将在完成时返回。如果两个线程同时调用该方法,则该正在运行的方法的两个实例将尝试更新同一列表,因此方法的结果将混合在一起。
It's not that the thread is safe or not. It's how state in your objects are protected from being updated by multiple threads. So, it's safe if only 1 thread can update a variable at a time so that you don't end up with some kind of inconsistent or unpredictable state.
An example of thread unsafe: You have an object that has an instance variable that stores a list of items that 1 method in that object uses to hold results of computations that it will return when it finishes. If two threads call that method at the same time, both instances of that running method will try to update the same list so the methods' results will be intermingled.