二十、线程同步机制(20、 Thread synchronization mechanism)

  • 并发:同一个对象被多个线程同时操作
  • 现实生活中,我们会遇到”同一个资源,多个人都想使用”的问题,比如,食堂排队打饭,每个人都想吃饭,最天然的解决办法就是:排队,一个个来。
  • 处理多线程问题时,多个线程访问同一个对象,并且某些线程还想修改这个对象.这时候我们就需要线程同步,线程同步其实就是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一个线程再使用。

由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制synchronized,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可,存在以下问题:

  • 一个线程持有锁会导致其他所有需要此锁的线程挂起:
  • 在多线程竞争下,加锁,释放锁会导致比较多的上下文切换和调度延时,引起性能问题;
  • 如果一个优先级高的线程等待一个优先级低的线程释放锁会导致优先级倒置,引起性能问题。
————————
  • Concurrency: the same object is operated by multiple threads at the same time
  • In real life, we will encounter the problem of “many people want to use the same resource”. For example, everyone wants to eat in the canteen. The most natural solution is to queue up and come one by one.
  • When dealing with multithreading, multiple threads access the same object, and some threads also want to modify the object At this time, we need thread synchronization. Thread synchronization is actually a waiting mechanism. Multiple threads that need to access this object at the same time enter the waiting pool of this object to form a queue, wait for the previous thread to be used, and then use the next thread.

Since multiple threads of the same process share the same storage space, it brings convenience and access conflict. In order to ensure the correctness of data access in the method, the lock mechanism synchronized is added during access. When one thread obtains the exclusive lock of the object and monopolizes resources, other threads must wait and release the lock after use. There are the following problems:

  • One thread holding a lock will cause all other threads that need the lock to hang:
  • In multi thread competition, locking and releasing locks will lead to more context switching and scheduling delays, resulting in performance problems;
  • If a high priority thread waits for a low priority thread to release the lock, it will lead to priority inversion and performance problems.