二、进程和线程(Process和Thread)(2、 Processes and threads)

Process和Thread

  • 说起进程,就不得不说下程序。程序是指令和数据的有序集合,其本身没有任何运行的含义,是一个静态的概念。
  • 而进程则是执行程序的一次执行过程,它是一个动态的概念。是系统资源分配的单位
  • 通常在一个进程中可以包含若干个线程,当然一个进程中至少有一个线程,不然没有存在的意义。线程是CPU调度和执行的的单位。
  • 注意:很多多线程是模拟出来的,真正的多线程是指有多个cpu,即多核,如服务器。如果是模拟出来的多线程,即在一个cpu的情况下,在同一个时间点,cpu只能执行一个代码,因为切换的很快,所以就有同时执行的错觉。

核心概念:

  • 线程就是独立的执行路径;
  • 在程序运行时,即使没有自己创建线程,后台也会有多个线程,如主线程,gc线程;main()称之为主线程,为系统的入口,用于执行整个程序
  • 在一个进程中,如果开辟了多个线程,线程的运行由调度器安排调度,调度器是与操作系统紧密相关的,先后顺序是不能人为干预的。
  • 对同一份资源操作时,会存在资源抢夺的问题,需要加入并发控制;线程会带来额外的开销,如cpu调度时间,并发控制开销。
  • 每个线程在自己的工作内存交互,内存控制不当会造成数据不一致
————————

Process和Thread

  • Speaking of the process, I have to say the procedure. Program is an ordered collection of instructions and data. It has no running meaning. It is a static concept.
  • The process is an execution process of the execution program, which is a dynamic concept. It is the unit of system resource allocation
  • Usually, a process can contain several threads. Of course, there is at least one thread in a process, otherwise it has no meaning. Thread is the unit of CPU scheduling and execution.
  • Note: many multithreads are simulated. Real multithreading refers to having multiple CPUs, i.e. multiple cores, such as servers. If it is a simulated multithreading, that is, in the case of one CPU, the CPU can only execute one code at the same time point. Because the switching is fast, there is the illusion of simultaneous execution.

Core concepts:

  • Threads are independent execution paths;
  • When the program is running, even if it does not create its own thread, there will be multiple threads in the background, such as main thread and GC thread; Main () is called the main thread, which is the entry of the system and is used to execute the whole program
  • In a process, if multiple threads are opened up, the operation of threads is scheduled by the scheduler. The scheduler is closely related to the operating system, and the sequence can not be interfered by human beings.
  • When operating on the same resource, there will be the problem of resource grabbing, and concurrency control needs to be added; Threads will bring additional overhead, such as CPU scheduling time and concurrency control overhead.
  • Each thread interacts in its own working memory. Improper memory control will cause data inconsistency