• 什么是线程安全和线程不安全


    线程安全一般都涉及到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 computer programming concept applicable in the context of multi-threaded 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.[1][2]

    A program may execute code in several threads simultaneously in a shared address space where each of those threads has access to virtually all of the memory 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 synchronization.

    Hi,

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

    http://en.wikipedia.org/wiki/Thread_safety

    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.

  • 相关阅读:
    MySQL for mac使用记录
    Jquery中$.get(),$.post(),$.ajax(),$.getJSON()的用法总结
    前端学数据库之基础操作
    前端CSS预处理器Sass
    ionic + cordova+angularJs 搭建的H5 App完整版总结
    HTML5的新语义化的标签
    angularJS- $http请求
    SEO优化---学会建立高转化率的网站关键词库
    当AngularJS POST方法碰上PHP
    从一个程序员的角度看——微信小应用
  • 原文地址:https://www.cnblogs.com/oxspirt/p/5018538.html
Copyright © 2020-2023  润新知