博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
什么是线程安全和线程不安全
阅读量:4699 次
发布时间:2019-06-09

本文共 2184 字,大约阅读时间需要 7 分钟。

线程安全一般都涉及到synchronized 就是一段代码同时只能有一个线程来操作 不然中间过程可能会产生不可预制的结果

---------------------------------------------------------

如果你的代码所在的进程中有多个线程在同时运行,而这些线程可能会同时运行这段代码。如果每次运行结果和单线程运行的结果是一样的,而且其他的变量的值也和预期的是一样的,就是线程安全的。

举例 比如一个 ArrayList 类,在添加一个元素的时候,它可能会有两步来完成:1. 在 Items[Size] 的位置存放此元素;2. 增大 Size 的值。

在单线程运行的情况下,如果 Size = 0,添加一个元素后,此元素在位置 0,而且 Size=1; 而如果是在多线程情况下,比如有两个线程,线程 A 先将元素存放在位置 0。但是此时 CPU 调度线程A暂停,线程 B 得到运行的机会。线程B也向此 ArrayList 添加元素,因为此时 Size 仍然等于 0 (注意哦,我们假设的是添加一个元素是要两个步骤哦,而线程A仅仅完成了步骤1),所以线程B也将元素存放在位置0。然后线程A和线程B都继续运行,都增加 Size 的值。 那好,现在我们来看看 ArrayList 的情况,元素实际上只有一个,存放在位置 0,而 Size 却等于 2。这就是“线程不安全”了。

 

Thread safety is a  concept applicable in the context of  programs. A piece of code is thread-safe if it only manipulates shared data structures in a manner that guarantees safe execution by multiple threads at the same time. There are various strategies for making thread-safe data structures.

A program may execute code in several threads simultaneously in a shared  where each of those threads has access to virtually all of the  of every other thread. Thread safety is a property that allows code to run in multi-threaded environments by re-establishing some of the correspondences between the actual flow of control and the text of the program, by means of .

 

Question
1

Hi,

A pice of code is thread safe if it is guaranteed to work correctly during simultaneous execution

for instance if a method does something like this

void Method(object myObject)    {      if (myObject == null) return;      // do something      string s = myObject.ToString();      myObject = null;    }

the code will explode if two threads are executing the same method with the same object and one thread executes myObject = null after the other thread just verified it isn't null, but before the other thread executes myObject.ToString.  The first thread will get a NullreferenceException at myObject.ToString(), which wouldn't make much sense since apparantly you just verified it wasn't null.

There are several techniques to prevent this from happening, most commonly using some form of lock to ensure only one thread at a time executes a particular piece of code.

转载于:https://www.cnblogs.com/oxspirt/p/5018538.html

你可能感兴趣的文章
BZOJ4516: [Sdoi2016]生成魔咒(后缀自动机)
查看>>
查看手机已经记住的WIFI密码
查看>>
最新版IntelliJ IDEA2019 破解教程(2019.08.07-情人节更新)
查看>>
C# 两个datatable中的数据快速比较返回交集或差集
查看>>
关于oracle样例数据库emp、dept、salgrade的mysql脚本复杂查询分析
查看>>
adb shell am 的用法
查看>>
iOS10 UI教程视图和子视图的可见性
查看>>
FindChildControl与FindComponent
查看>>
中国城市json
查看>>
android下载手动下载Android SDK
查看>>
C++学习:任意合法状态下汉诺塔的移动(原创)
查看>>
leetcode133 - Clone Graph - medium
查看>>
一点小基础
查看>>
PHP 自动加载类 __autoload() 方法
查看>>
JDK中的Timer和TimerTask详解(zhuan)
查看>>
【python练习】ATM&购物商城程序
查看>>
nginx 日志问题(\x22)
查看>>
装饰器、迭代器、生成器
查看>>
类对象作为类成员
查看>>
面向对象和面向过程的区别及优劣对比详解
查看>>