Java multithreading creation and basic principles

Java multithreading

1.1 Concurrency and parallelism

  • Concurrency : Refers to two or more events occurring in the same time period .
  • Parallel : Refers to two or more events occurring at the same time (simultaneously).

In the operating system, multiple programs are installed, and concurrency refers to multiple programs running at the same time in a period of time. In a single CPU system, only one program can be executed at a time, that is, these programs in a microscopic view. It is a time-sharing alternate operation, but it gives the impression of simultaneous operation, because the time of the time-sharing alternate operation is very short.

In a multiple CPU system, these programs that can be executed concurrently can be distributed to multiple processors (CPUs) to achieve parallel execution of multiple tasks, that is, each processor is used to process a program that can be executed concurrently. Multiple programs can be executed simultaneously. At present, the multi-core CPU in the computer market is a multi-core processor. The more cores, the more programs can be processed in parallel, which can greatly improve the efficiency of computer operation.

Note: A computer with a single-core processor certainly cannot process multiple tasks in parallel, only multiple tasks can run concurrently on a single CPU. In the same way, threads are the same. From a macro perspective, threads run in parallel, but from a micro perspective, they run serially, that is, one thread runs one thread. When the system has only one CPU, the thread will run To execute multiple threads in a certain order, we call this situation thread scheduling.

1.2 Threads and processes

  • Process : Refers to an application program running in memory. Each process has an independent memory space. An application program can run multiple processes at the same time; a process is also a one-time execution process of a program and is the basic unit of the system to run a program; system Running a program is the process of a process from creation, operation to death.

  • Thread : A thread is an execution unit in a process, responsible for the execution of the program in the current process, and there is at least one thread in a process. There can be multiple threads in a process, and this application can also be called a multithreaded program.

    In short: after a program runs, there is at least one process, and a process can contain multiple threads

We can go to the task bar at the bottom of the computer and right-click to open the task manager to view the progress of the current task:

Thread scheduling:

  • Time-sharing scheduling

    All threads take turns to use the right to use the CPU, and evenly distribute the time that each thread occupies the CPU.

  • Preemptive scheduling

    Give priority to high-priority threads to use the CPU. If the threads have the same priority, one will be randomly selected (thread randomness). Java uses preemptive scheduling.

    • Set thread priority

    • Detailed explanation of preemptive scheduling

    Most operating systems support the concurrent operation of multiple processes, and almost all current operating systems support running multiple programs at the same time. For example: Now we use the editor and screen recording software while in class, and also open the drawing board, dos window and other software at the same time. At this time, these programs are running at the same time, "it feels like these software are running at the same time."

    In fact, the CPU (central processing unit) uses preemptive scheduling mode to switch between multiple threads at high speed. For a core of the CPU, only one thread can be executed at a certain time, and the switching speed of the CPU between multiple threads is faster than we feel, and it seems to be running at the same time.

    In fact, multi-threaded programs cannot improve the running speed of the program, but it can improve the running efficiency of the program and make the CPU usage higher.

1.3.1 Create a thread class (inherit the Thread class method)

Java uses java.lang.Threadclasses to represent threads , and all thread objects must be instances of the Thread class or its subclasses. The role of each thread is to complete a certain task, in fact it is to execute a section of program flow, that is, a section of code that is executed sequentially. Java uses threaded execution to represent this program flow. The steps to create and start multithreading in Java by inheriting the Thread class are as follows:

  1. Define a subclass of the Thread class and rewrite the run() method of this class. The method body of the run() method represents the task that the thread needs to complete, so the run() method is called the thread execution body.
  2. Create an instance of the Thread subclass, that is, create a thread object
  3. Call the start() method of the thread object to start the thread

code show as below:

Test category:

public class Demo01 {
    
    
	public static void main(String[] args) {
    
    
		//创建自定义线程对象
		MyThread mt = new MyThread("新的线程!");
		//开启新线程
		mt.start();
		//在主方法中执行for循环
		for (int i = 0; i < 10; i++) {
    
    
			System.out.println("main线程!"+i);
		}
	}
}

Custom thread class:

public class MyThread extends Thread {
    
    
	//定义指定线程名称的构造方法
	public MyThread(String name) {
    
    
		//调用父类的String参数的构造方法,指定线程的名称
		super(name);
	}
	/**
	 * 重写run方法,完成该线程执行的逻辑
	 */
	@Override
	public void run() {
    
    
		for (int i = 0; i < 10; i++) {
    
    
			System.out.println(getName()+":正在执行!"+i);
		}
	}
}

1.3.2 Create thread class (implement Runnable interface method)

Proceed as follows:

  1. Define the implementation class of the Runnable interface and rewrite the run() method of the interface. The method body of the run() method is also the thread execution body of the thread.
  2. Create an instance of the Runnable implementation class, and use this instance as the Thread target to create a Thread object, which is the real thread object.
  3. Call the start() method of the thread object to start the thread
public class MyRunnable implements Runnable{
    
     
	@Override 
	public void run() {
    
     
		for (int i = 0; i < 20; i++) {
    
    
	 		System.out.println(Thread.currentThread().getName()+" "+i); 
		} 
	} 
}
public class Demo {
    
     
	public static void main(String[] args) 
	{
    
       //创建自定义类对象 线程任务对象 MyRunnable mr = new MyRunnable(); 
	//创建线程对象 Thread t = new Thread(mr, "小强");
	 t.start(); 
	 	for (int i = 0; i < 20; i++) 
		 {
    
     
		 	System.out.println("旺财 " + i); 
 		  } 
 	}
}

By implementing the Runnable interface, this class has the characteristics of a multi-threaded class. The run() method is an execution target of a multithreaded program. All the multithreaded code is in the run method. The Thread class is actually a class that implements the Runnable interface. When starting multithreading, you need to construct an object through the Thread(Runnable target) construction method of the Thread class, and then call the start() method of the Thread object to run the multithreaded code.

In fact, all multi-threaded code is run by running the start() method of Thread. Therefore, whether it is to inherit the Thread class or implement the Runnable interface to achieve multithreading, the thread is finally controlled through the API of the Thread object. Familiar with the API of the Thread class is the basis for multi-threaded programming.

Summary: The advantages of implementing the Runnable interface over inheriting the Thread class:

  1. It is suitable for multiple threads of the same program code to share the same resource.
  2. You can avoid the limitations of single inheritance in java.
  3. Increase the robustness of the program, realize decoupling operation, the code can be shared by multiple threads, and the code and thread are independent.
  4. The thread pool can only be placed into threads that implement Runable or Callable classes, and cannot be placed directly into classes that inherit Thread.

Expansion: In java, at least 2 threads are started each time the program runs. One is the main thread and the other is the garbage collection thread. Because every time a class is executed using the java command, a JVM is actually started, and each JVM actually starts a process in the operating system.

1.4 Principle

When the program starts and runs main, the java virtual machine starts a process, and the main thread main is created when main() is called. With the call to the start() method of the mt object, another new thread is also started, so that the entire application runs in multiple threads. Through this picture, we can clearly see the execution flow of multithreading, so why can concurrent execution be completed?

How does it work in memory when multi-threaded execution? The above program is taken as an example to illustrate: When multi-threaded execution, in the stack memory, in fact, each execution thread has its own stack memory space. Push and pop the method stack.
Insert picture description here

1.5 Thread class

Construction method

  • public Thread(): Allocate a new thread object.
  • public Thread(String name): Allocate a new thread object with a specified name.
  • public Thread(Runnable target): Allocate a new thread object with the specified target.
  • public Thread(Runnable target, String name): Allocate a new thread object with the specified target and specify the name.
    Common method
  • public String getName(): Get the current thread name.
  • public void start(): Cause this thread to start execution; the Java virtual machine calls the run method of this thread.
  • public void run(): The task to be executed by this thread defines the code here.
  • public static void sleep(long millis): Suspend the currently executing thread for the specified number of milliseconds (temporarily stop execution).
  • public static Thread currentThread(): Returns a reference to the thread object currently being executed.

Guess you like

Origin blog.csdn.net/david2000999/article/details/113858988