Java Multithreading Basics | JUC Concurrent Programming Basics

1. Basic concepts of processes and threads

Processes and threads do not exist at the beginning, but concepts that appear as needed.

1. The background of the process

At first, the computer could only accept some specific instructions. When the user inputs an instruction, the computer will perform an operation. However, the speed of user input is far lower than the speed of computer calculation, so the computer spends a lot of time waiting for user input, that is, the CPU is always in an idle state, and the utilization rate of the CPU is very low.

batch operating system

Later, there was a batch operating system, which wrote some series of instructions into a list, and gave the list to the computer at one time, and then the computer would read the instructions line by line and output the result to another disk.

Although the emergence of the batch operating system has improved the efficiency of the computer, because the command operation mode of the batch operating system is still serial, only one program is always running in the memory . This kind of batch processing operating system is not ideal, because at the same time, the CPU can only execute the instructions of one program, that is, only one program can run in the memory.

Proposal of process

Since only one program can run in memory, computer scientists came up with the concept of a process.

A process is the space allocated by an application program in the memory, that is, multiple programs can run in the memory at the same time , and each application program (process) does not interfere with each other. Each process saves the state of the program running.

Program: Refers to a collection of codes that can accomplish certain functions.

The CPU in a computer runs each process in time slices. The CPU will allocate a time slice to each process. If the process is still running when the time slice ends, the process will be suspended and the CPU will be allocated to another process (this process is context switching). If the process blocks or ends before the time quantum expires, the CPU switches immediately without waiting for the time quantum to run out.

It should be noted that context switching by the CPU is a very time-consuming operation, because the state of the current process (process identification, resources used by the process, etc.) must be saved before the process is switched, so that it is convenient to obtain the CPU time slice next time according to the previously saved The state is restored and execution continues.

Using the method of CPU time slice + process, macroscopically, it feels that multiple tasks are executed in the same time period. That is because the CPU's calculation speed is too fast, so it looks like concurrent processing tasks. In fact, for a single-core CPU, only one program is executing at any time.

Concurrency: Processing multiple tasks at the same time.

Parallelism: Processing multiple tasks at the same time.

Further increase in operating system requirements

Although the appearance of the process has greatly improved the performance of the operating system, as time goes by, people are not satisfied that a process can only do one thing in a period of time. If a process has multiple subtasks, they can only be executed one by one. These subtasks greatly affect efficiency.

For example: the anti-virus software on our computer, we cannot scan for junk while scanning for viruses. We have to wait for the virus scan to complete before we can scan for junk.

thread presentation

Can we make these subtasks execute at the same time? So the concept of thread was put forward. A thread is a unit smaller than a process. A program is a process, and a process can contain one or more threads.

image-20230405200232690

For example: the antivirus software on our computer can scan for viruses and garbage at the same time.

Processes make the concurrency of the operating system possible, and threads make the internal concurrency of processes possible.

Since processes can also achieve concurrency, why do we need to propose processes?

  • Process communication is more complicated, data is not easy to share, and there are memory barriers between different processes. The thread facilitates the sharing of data and the communication between threads.
  • Processes are heavyweight, and the overhead of switching processes is relatively high. Not only do registers and stack information need to be saved, resource allocation and recycling, and paging are also required. The thread only needs to save registers and stack information, and the overhead is relatively small.

Two, multithreading

Above we talked about the reasons for processes and threads. So how to create threads in Java?

1. Inherit the Thread class

class MyThread extends Thread {
    
    

    @Override
    public void run() {
    
    
        System.out.println(Thread.currentThread().getName());
    }
}
public class Demo04 {
    
    
    public static void main(String[] args) {
    
    
        MyThread thread1 = new MyThread();
        thread1.setName("子线程1");
        thread1.start();
        MyThread thread2 = new MyThread();
        thread2.setName("子线程2");
        thread2.start();
        System.out.println(Thread.currentThread().getName());
    }
}

Note: The same thread cannot call start()the method multiple times, otherwise IllegalThreadStateExceptionan exception .

start() source code:

private volatile int threadStatus = 0;
public synchronized void start() {
    
    
    /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
    if (threadStatus != 0)
        throw new IllegalThreadStateException();

    /* Notify the group that this thread is about to be started
         * so that it can be added to the group's list of threads
         * and the group's unstarted count can be decremented. */
    group.add(this);

    boolean started = false;
    try {
    
    
        start0();
        started = true;
    } finally {
    
    
        try {
    
    
            if (!started) {
    
    
                group.threadStartFailed(this);
            }
        } catch (Throwable ignore) {
    
    
            /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
        }
    }
}

private native void start0();

After analyzing the source code , it is found that the value that will change after threadStatus = 0calling the local method will change, so an exception will be reported when the method is called for the second time .start0()threadStatusstart()IllegalThreadStateException

2. Implement the Runnable interface

Threads are created by inheriting the Thread class above, but we know that in Java it is single inheritance and multiple implementations. If a class inherits the Thread class, it cannot explicitly inherit other classes. If we want to create a new thread task and inherit other classes, how do we achieve it?

In the constructor of Thread, it is supported to create a thread by passing an implementation class of the Runnable interface.

image-20230405203241447

class MyCustomThread implements Runnable {
    
    

    @Override
    public void run() {
    
    
        System.out.println(Thread.currentThread().getName());
    }
}
public class Demo05 {
    
    
    public static void main(String[] args) {
    
    
        Thread thread = new Thread(new MyCustomThread());
        thread.start();
    }
}

We can also simplify the above code, such as writing it as an anonymous inner class object, or writing it as a lamdab expression.

What is an anonymous inner class object?

An anonymous inner class refers to an inner class without a name, which directly implements an interface or inherits from a class when declared, and is directly created and instantiated when used. Anonymous inner classes are very commonly used in Java, which can simplify the writing of code, make the code more concise, and also allow programmers to hide the implementation details of the code to a certain extent.

Format:

new parent class constructor <actual parameter list> implements interface name <generic parameter list> {external class member variable, method; [internal class member variable] [internal class method]}

After JDK 8, if you do not modify external variables, you can directly access them without final modification.

public class OuterClass {
     
     
    public void myMethod() {
     
     
        final int x = 3; // 将x声明为final
        new Thread(new Runnable() {
     
     
            @Override
            public void run() {
     
     
                x++; // 编译错误,无法修改x的值
                System.out.println(x);
            }
        }).start();
    }
}

Anonymous inner class object:

public class Demo05 {
    
    
    public static void main(String[] args) {
    
    
        Thread thread = new Thread(new Runnable {
    
    
            @Override
            public void run() {
    
    
                System.out.println(Thread.currentThread().getName());
            }
        });
        thread.start();
    }
}

To distinguish between anonymous objects, anonymous inner class objects, and inner classes.

Anonymous object: No name is given to the created object.

For example: new MyThread().

Inner class: A class defined inside a class.

For example:

class OutterClass {
     
     
    // 外部类成员
    class InnerClass {
     
     
        // 内部类成员
    }
}

Anonymous inner class object: No name is given to the instance of the inner class.

We can further simplify the code and write it as a lamdab expression.

public class Demo05 {
    
    
    public static void main(String[] args) {
    
    
        new Thread(() -> System.out.println(Thread.currentThread().getName())).start();
    }
}

If you are not familiar with lamdab, you can search and learn online.

To use lamdab, the JDK version used must be greater than or equal to 8.


More content welcome to visit my blog .

Guess you like

Origin blog.csdn.net/qq_43907505/article/details/130054237