The article directories

  • 1. Programs, processes, and threads
    • 1.1 application:
    • 1.2 process:
    • 1.3 the thread:
    • 1.4 Parallelism and Concurrency
    • 1.5 Single-Core CPU Multi-core CPU
  • 2. Creating and using threads
    • 2.1 Thread class
    • 2.2 Two ways to create threads in the API
      • Method 1: Inherit Thread
      • Method 2: Implement the Runnable interface
      • Added Method 1: Implement the Callable interface
      • New method 2: Using a thread pool
      • The connection and difference between inheritance and implementation
  • 3. Thread scheduling
  • 4. Priority of the thread
  • 5. Classification of threads
  • 6. Thread lifecycle

1. Programs, processes, and threads

1.1 application:

  • Is a set of instructions written in a language to accomplish a specific task. It’s a piece of static code, a static object.

1.2 process:

  • An execution of a program (a running program) is a dynamic process, with its own production, existence, and extinction processes. — Life cycle;
  • The program is static, the process is dynamic;
  • Processes are the unit of resource allocation, and the system allocates a different memory area to each process at runtime.

1.3 the thread:

A process can be further refined into a thread, which is an execution path within a program.

  • Multithreading is supported if a process executes multiple threads in parallel at the same time.
  • Thread as a scheduling and execution unit, each thread has an independent running stack and program counter (PC), thread switching overhead is small;
  • Multiple threads in a process share the same memory unit/memory address space -> they allocate objects from the same stack and have access to the same variables and objects, which makes communication between threads easier and more efficient. But multiple threads operating on shared system resources can be a security risk.

1.4 Parallelism and Concurrency

  • Parallel: Multiple cpus perform multiple tasks simultaneously. For example: multiple people doing different things at the same time.
  • Concurrency: a CPU (using time slices) executes multiple tasks simultaneously. For example: seckill.

1.5 Single-Core CPU Multi-core CPU

  • Single-core CPU, in fact, is a false multithreading, because in a time unit, can only execute the task of one thread. For example, if there are multiple lanes, but only one person is collecting tolls, the CPU is like a toll collector. If a person does not want to pay, the toll collector can “hang” him (wait for him to figure out, ready money, and then charge). But because the CPU time unit is so short, you can’t feel it.
  • If it is multi-core, can better play the efficiency of multi-threading. (Today’s servers are multi-core.)
  • A Java application java.exe has at least three threads: the main() thread, the garbage collection thread, and the exception handling thread. Of course, if an exception occurs, the main thread will be affected.

2. Creating and using threads

The JVM for the Java language allows programs to run multiple threads, which are represented by the java.lang.Thread class… Features of the Thread class

Each Thread completes its operations through the run() method of a particular Thread object. The body of the run() method is often called the Thread body. The Thread is started by the start() method of the Thread object, rather than by calling run() directly.Copy the code

2.1 Thread class

The constructor

Thread(String threadName): creates a Thread and specifies the instance name of the Thread. Thread(Runnable target): specifies the target object for creating the Thread. It implements the run method in the Runnable interface Thread(Runnable target, String name): Creates a new Thread objectCopy the code

2.2 Two ways to create threads in the API

There are two ways to create a new thread of execution prior to JDK1.5:

Implement the Runnable interface by inheriting the Thread classCopy the code

Method 1: Inherit Thread

1) Define subclasses that inherit from Thread. 2) Overwrite the run method of Thread class in subclass. Create Thread subclass object, that is, create Thread object. 4) Call thread object start method: start the thread, call the run method.Copy the code

Note:

1. If you call the run() method manually, it is just a normal method and does not enable multithreaded mode. 2. The run() method is called by the JVM, and when it is called, and the process it executes, is controlled by the OPERATING system's CPU scheduling. 3. To start multithreading, you must call the start method. 4, a thread object can only be called once the start () method starts, if repeated calls, would throw more abnormal "lllegalThreadStateException".Copy the code

Method 2: Implement the Runnable interface

1) Define subclasses to implement the Runnable interface. 2) Override the Runnable interface run method in a subclass. 3) Create a Thread object with a Thread constructor. 4) Pass the Runnable interface subclass object as an actual parameter to the Thread constructor. 5) Call the Thread start method: to start the Thread, call the Runnable subclass interface run method.Copy the code

Added Method 1: Implement the Callable interface

Callable is more powerful than RunnableCopy the code
  • In contrast to the run() method, there can be a return value

  • Method can throw an exception

  • Generic return values are supported

  • You need the FutureTask class, for example, to get the return result

    The Future interface

  • You can cancel the execution result of a Runnable or Callable task, query whether the task is complete, and obtain the result.

  • Futrue Task is the only implementation class of the Futrue interface

  • FutureTask implements both Runnable and Future interfaces. It can be either executed by the thread as a Runnable or returned by a Callable as a Future

New method 2: Using a thread pool

Background: Heavily used resources that are frequently created and destroyed, such as threads in concurrent situations, have a significant impact on performance. Create several threads in advance and put them into the thread pool. It can avoid frequent creation and destruction and realize reuse. Similar to public transportation in life. Benefits: • Improved response time (less time to create new threads) • Reduced resource consumption (reuse of threads in the thread pool, not need to be created every time) • Ease of thread management

CorePoolSize: specifies the size of the core pool. MaximumPoolSize: specifies the maximum number of threads. KeepAliveTime: specifies the maximum length of time a thread can hold without any task before terminatingCopy the code

The connection and difference between inheritance and implementation



The difference between

Inheriting Thread: Thread code is stored in the Thread subclass run method. Implement Runnable: Thread code exists in the run method of a subclass of the interface.Copy the code

Benefits of the implementation approach

Avoiding the limitations of single inheritance Multiple threads can share objects of the same interface implementation class, making it ideal for multiple threads to handle the same resource.Copy the code

Void start(): starts the Thread and executes the object’s run() method. Run (): the operation that the Thread performs when it is scheduled. String getName): Returns the name of the Thread Static Thread currentThread(): returns the currentThread. In the Thread subclass this is commonly used for the main Thread and Runnable implementation class static void yield(): The Thread yields • Suspends the currently executing Thread to yield execution to a Thread of the same priority or higher • Ignores this method if there are no threads of the same priority in the queue .join(): When a program calls another thread’s join() method in the execution stream, the calling thread will be blocked until the join thread joined by the join() method completes. (specified time: ms) • The current active thread in the specified period of time to give up the CPU control, so that other threads have a chance to be executed, after the time is up to queue again. • Throws InterruptedException.stop(): forces the thread’s life to end. Not recommended. Boolean isAlive(): returns a Boolean to determine whether the thread is still alive

3. Thread scheduling

4. Priority of the thread

5. Classification of threads

Threads in Java fall into two categories: daemon threads and user threads. • They are identical in almost every respect, the only difference being determining when the JVM leaves. • Daemons are used to service user threads, and a user thread can be turned into a daemon thread by calling Thread.setdaemon (true) before the start() method. • Java garbage collection is a typical daemon thread. • If the JVM is full of daemons, the current JVM exits. • Image understanding: rabbit dead dog cook, birds all bow hidden

6. Thread lifecycle

To implement multithreading, you must create a new thread object in the main thread. The Java language uses objects from the Thread class and its subclasses to represent threads, which typically undergo five states during their full life:

• New: When an object of the Thread class or its subclass is declared and created, the newly created Thread object is in the new state.

• Ready: After a thread is started (), it enters the thread queue and waits for a CPU slice. It is ready to run but has not been allocated CPU resources.

• Run: When a ready thread is scheduled and CPU resources are acquired, the run() method defines the actions and functions of the thread.

• Block: in some special cases, when the input/output operation is suspended or executed artificially, the CPU is released and its execution is temporarily suspended, and the execution enters the blocking state.

• Death: a thread has completed all of its work or the thread has been forcibly terminated prematurely or an exception has occurred resulting in termination.