Java 并发编程之线程安全(随手笔记)

一:共享对象:

1 锁可以保证可见性和原子性;volatile变量只能保证可见性

2 Do not allow the reference to escape during construction

3 建议:在构造函数里声明一个线程,提供一个初始化方法strart线程(不要在构造函数里启动线程)。

4 桟约束:桟约束是一种特殊的线程约束,对象只能通过本地变量访问。

5 ThreadLocal:把每一个线程的值放到一个持有值的对象中。

6 immutability(不可变性):immutable objects are always thread-safe。

      一个对象是不可变的:

      1)它的状态在构造之后不能变

      2)它的所有域都是final的

      3)它是被合理构造(在构造期间不会escape)

      创建一个不可变的类来持有要原子操作的变量,在构造参数中初始化它们,确保对这些变量操作的原子性。

      不可变的对象可以被没加同步的线程安全的使用,发布。

7 安全发布:

      1 合适的构造对象,安全发布:

          1)在静态块中初始化对象

          2)把引用保存在volatile域或者原子引用中

          3)把引用保存在final域中

          4)把引用保存在有锁维持的域中

       2 高效不可变对象:状态不变的对象成为搞笑不可变对象

8 在并发编程中使用共享对象最有用的策略:

    1 线程限制:对象被一个线程持有,并且只能被拥有的线程修改

    2 共享只读:

    3 共享线程安全:

    4 guarded

9 java does not provide any mechanism for safely forcing a thread to stop what it is doing . Instead , it provides interruption , a cooperative mechanism that lets one thread ask another to stop what it is doing(Java 没有提供任何机制安全地停止一个正在运行的线程,相反,提供了interruption,一个友好的机制使一个线程让另一个线程停止它正在做的事情)

10 任务取消的原因:

      1)用户请求取消

      2)超时:在预定时间内没获得结果,正在执行的任务都会被取消

      3)应用事件:当一个任务找到了解决方案,其他的任务都会被取消

      4)错误:一个任务发生异常,其他任务会被取消

      5)停止:应用或者服务停止,正在被处理的或者排队等待的任务,优雅停止时,正在处理的任务可以执行完成,立刻停止时,正在被执行的任务可能被取消

11 calling interrupt does not necessarily stop the target thread from doing what it is doing ; it merely delivers the message that interruption has been requested.(调用interrupt方法不是停止目标线程正在干的事情;它仅仅把interrupt请求信息传输过去)A good way to think about interruption is that it does not actually interrupt a running thread ; it just requests the thread interrupt itself at the next convenient opportunity(一个正确的理解interruption的方法是它实际上没interrupt一个正在运行的线程,它仅仅请求线程在下个方便的时机interrupt它自己)

12 interruption is usually the most sensible way to implement cancellation (interruption通常是实现取消最明智的方式)

13 The most  sensible interruption policy is some form of thread-level or service-level cancellation; exit as quickly as practical , cleaning up if necessary , and possibly notifying some owning entity that the thread is exiting.(最明智的interruption策略是线程级或者服务级的取消:最快的退出,必要的时候清除,通知拥有的实体线程退出了)

14 A thread should be interrupted only by its owner.(线程只能被它的拥有者interrupt)

15 Because each thread has its own interruption policy,you should not interrupt a thread unless you know what interruption means to that thread(因为每一个线程有它自己的interrupt策略,你不应该interrupt一个线程除非你知道interrupt那个线程意味着什么)


你可能感兴趣的:(Java 并发编程之线程安全(随手笔记))