01-Overview of processes and threads

Related concepts of processes and threads

概述

进程是一个运行中的应用程序, a process is an executing software

  • Every time a software is opened, it is equivalent to starting a process. The operating system will allocate a memory space for the process. The memory of process A and process B is independent and not shared.

Threads are created by processes, and a process can start multiple threads.线程是一个进程中的执行场景/执行单元

  • Opening Xunlei is equivalent to starting a process. Downloading multiple files in Xunlei is equivalent to opening multiple threads in the Xunlei process.

By default, our process will end only when all threads in the entire process end.main方法结束只是主线程结束了, when the main stack is empty, other stacks (threads) may still be pushing and popping the stack.

  • 单线程: Indicates that only one thread is allowed to execute at the same time
  • 多线程: Indicates that multiple threads can be executed at the same time. Java supports multi-threading mechanism. The purpose is to improve the processing efficiency of the program.

Thread A and Thread B共享堆内存和方法区内存, but Thread A and Thread B栈内存独立 are one thread and one stack

  • Multi-thread concurrency: When 10 threads are started, there will be 10 stack spaces. Each stack and each stack execute independently without interfering with each other. The relationship between multiple threads is concurrent or parallel.

Insert image description here

并发和并行

Concurrency and parallelism are situations where multiple threads are executed at the same time.

  • 并发: A single-core CPU can only process one thing at the same time, but due to the extremely fast processing speed of the CPU, multiple threads frequently switch between executions, giving the impression that multiple threads are executing at the same time.
  • 并行: For multi-core CPU, multiple tasks can be executed at the same time at the same time. For example, a 4-core CPU means that 4 processes can be executed concurrently at the same point in time.

Get the number of CPUs of the current computerRunTime类的availableProcessors方法

//单例设计模式
RunTime runtime = RunTime.getRunTime;
int cpuNums = runtime.availableProcessors();
System.out.println("当前电脑的cpu数量是" + cpuNums)

Java程序即进程

Java程序的流程: Start the JVM process first –> JVM then starts a main thread responsible for calling the main method and a garbage collection thread responsible for taking care of the garbage collection (at least these two threads are concurrent)

  • Executing the start method of the thread object in the main thread can start other sub-threads. At this time, the main thread and sub-threads are executed at the same time. By default, our process will end when all threads of the entire process end.

Usejconsole命令 to monitor the execution of threads

Insert image description here

Guess you like

Origin blog.csdn.net/qq_57005976/article/details/134997807