Replay Java Memoir (12): Use of Java 12 thread, Java 12
Processes and threads
Process: A sub-Program executed in an operating system, including virtual cpu, code, and Data DOS
Multi-process: Multiple subprograms executed in one operating system improve cpu usage
Thread: subprogram stream that is executed simultaneously in a process
Multithreading: Several subprogram streams that are executed simultaneously in a process
Differences between processes and threads:
Processes have independent process space (data storage) and are independent of each other.
The thread heap space is shared, the stack space is independent, and the resources occupied by the thread are relatively small, which can affect each other.
How to use processes in Java
Class that calls the local program
Runtime: The current running environment exec returns the result of process
Process: Process
Java program running
Jvm running: Process-level running. Once the JVM ends, the threads above the JVM are destroyed.
Java code is interpreted (run) in Jvm, and every executable Java program should be treated as a thread
A -- main thread
-- Enable other threads through the main thread and end the main method --> end of the main thread
-- The thread opened by main is still being executed
B -- main
Features of threads:
1. Mutual influence between threads
2. Priority exists between threads
How to write threads in java
Thread running
New -------> start -- Automatic --> run <-----> pause (wait/sleep)
--------> Destroy (distory)
Main method: It is a special thread with the highest priority
The essence of the thread: run: is an execution method run ()
-- Extends
Thread class: Thread: requires sub-classes to implement the run method (rewrite)
-- Implementation method implements
Thread running mode: Runnable: run Method