java多线程知识整理

java多线程知识整理 本文不是入门篇,仅记录容易出错的知识点

为什么需要多线程

根本原因:

  1. 同一段时间尽量做更多的事;
  2. 充分发挥CPU的功能,避免浪费CPU资源;
  3. 同一时间需要做不同的事;

多线程的核心问题

  1. 对同一个变量的读写,导致脏写(数据库事务概念);

  2. 多个线程相互协作,如何通信,比如线程A依赖线程B的某个资源

如果没有特别的控制和机制,多个线程对同一个变量的读写,容易造成中间结果相互覆盖的情形,

类似于数据库事务中的脏写

有时线程A的执行需要线程B的某个资源,或者等线程B执行完某个操作之后,才能往下执行.

竞态条件

竞态条件,说得通俗一点,就是线程A 需要判断一个变量的状态,然后根据这个变量的状态来执行某个操作。 在执行这个操作之前,这个变量的状态可能会被其他线程修改。

参考:http://hw1287789687.iteye.com/blog/2007134

多线程争抢的是什么资源?

  1. CPU资源;
  2. lock(ownership of this monitor/object's monitor)

获取CPU资源,线程状态 从就绪状态进入运行状态;

获取 lock,则由blocked状态进入就绪(runnable)状态

容易弄混的

  1. 调用完wait()之后,会往下执行吗?
    不会,会做两件事 (1) 释放锁;
    (2)进入等待队列;

  2. 线程A 先调用wait(),线程B 在同步代码块中调用 notifyAll(),线程A会马上执行吗? 不会.官网文档:

The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution

B线程调用notifyAll() 之后,线程A 从等待队列进入 锁池,等待获取同步锁,并不会马上执行.

  1. 可以任意执行wait()吗?
    不可以,必须先获取锁,才有资格执行wait().

Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0). The current thread must own this object's monitor.

哪些手段保证多线程的安全?

  1. 使用synchronized;
  2. 使用读写锁

总结

java 多线程安全机制和数据库事务的隔离级别 ,是一样的套路,
java中,同一个时间片,只允许一个线程进入同步代码块,来保证安全;
数据库事务中,通过共享读锁,排它锁,行级所,表级锁,来保证对于同一个表或同一行数据,只能有一个事务进入

参考:https://blog.csdn.net/evankaka/article/details/44153709
http://www.importnew.com/26850.html http://www.hollischuang.com/archives/943

 https://my.oschina.net/huangweiindex/blog/1919895

猜你喜欢

转载自hw1287789687.iteye.com/blog/2428374