How cruel! It’s really Ali’s technology. This set of multithreaded triple questions almost makes me doubt my life!

Time:2021-7-5

preface

Many friends face multithreading problems are very big, because it is difficult to use their own projects, but all high paid job interviews will ask.. After all, most factories now use multithreading and high concurrency, so it’s impossible to understand this content thoroughly.

Today, as the foundation of multithreading, let’s talk about the following issues:

  1. Why multithreading?
  2. Program vs process vs thread
  3. Four ways to create threads?

I have prepared the interview materials of the first-line companies, my original ultra hard core PDF technical documents, and many sets of resume templates (constantly updated) that I have carefully prepared for you. I hope you can find your favorite job! Friends in needClick here for commentsDownload by yourself, hope to help you!
How cruel! It's really Ali's technology. This set of multithreaded triple questions almost makes me doubt my life!

Why multithreading

The emergence of any technology is to solve the existing problems.

Before the Internet is mostly stand-alone services, small volume; Now cluster services are more common. If multiple users visit the server at the same time, there will be many threads accessing concurrently.

For example, in the e-commerce system, a large number of users visit the server at the same time, such as rush buying at the same time, so the company’s development is basically multi-threaded.

The use of multithreading does improve the efficiency of running, but at the same time, we also need to pay special attention to the addition, deletion and modification of data, which is the problem of thread safety, as mentioned beforeHashMap vs HashTableVector vs ArrayList

There are many ways to ensure thread safety, such as locking, but there may be other problems, such as deadlock, so multithreading related problems will be more troublesome.

Therefore, we need to understand the principle of multithreading and the problems it may cause, and how to solve the problem, in order to get a high salary position.

Process vs thread

program program

When it comes to process, we have to talk about procedure first.

A program, to put it bluntly, is a code, or a set of instructions. For example, “wechat. Exe” is a program, and this file is ultimately taken to the CPU for execution.

Process

When the program runs, it’s aprocess

thereforeThe program is “dead” and the process is “alive”

For example, in the task manager is a process, is “moving” applications.

How cruel! It's really Ali's technology. This set of multithreaded triple questions almost makes me doubt my life!

Q: Are these processes executed in parallel?

A single core CPU can only execute one process in a time slice. But because of its fast switching speed, we can’t feel it, which creates the illusion of multi process( Multi core CPU is really parallel execution.)

Q: What if the process is not finished?

When process a has finished executing a time slice, but it has not finished yet, in order to facilitate the next execution, it is necessary to save the data information that has just been executed, which is called “save scene”.

Then, when the next time we get the resources to execute, we first “restore the scene” and then continue to execute.

It goes back and forth..

This repeated save, restore, ah, are extra overhead, but also slow down the program execution.

Q: Is there a more efficient way?

If two threads belong to the same process, there is no need to save and restore the scene.

This is the idea of NiO model and the reason why NiO model is much more efficient than bio model. We will talk about it later.

Thread

Thread is the specific execution path in a process, which is the real work.

In a process, a time slice can only be executed by one thread, but because the switching speed of time slice is very fast, it seems to be executed at the same time.

There is at least one thread in a process. For example, the main thread is what we usually writemain()Function, yesUser thread; alsogcThreads are produced by the JVM and are responsible for garbage collectionDaemons

How cruel! It's really Ali's technology. This set of multithreaded triple questions almost makes me doubt my life!

Each thread has its ownStack stackTo record the calling relationship between methods in the thread;

But all threads in a process areShared heap heapYes.

So different processes can’t access each other’s memory. Each process has its own memoryMemory space memeory spaceThat is to sayvirtual memory virtual memory

Through this virtual memory, each process feels that it has the whole memory space.

The mechanism of virtual memory is to shield the limitation of physical memory.

Q: What if physical memory is used up?

Using the hard disk, such as the paging file of windows system, is to put part of the virtual memory on the hard disk.

Correspondingly, the program will run very slowly at this time, because the reading and writing speed of the hard disk is much slower than that of the memory, which is the slowness we can feel. This is why the computer will become stuck if you open more programs.

Q: How big is the virtual memory?

For 64 bit operating system, each program can use 64 binary bits, that is2^64Such a big space!

If the binary related content is not clear, the corresponding reply is obtained in the official account.

summary

To sum up, in a time slice, a CPU can only execute one process.

After the CPU allocates resources to a process, the process starts to run; The thread in the process to seize resources, a time slice only one thread can execute, who first grab is who.

How cruel! It's really Ali's technology. This set of multithreaded triple questions almost makes me doubt my life!

Multiprocess vs Multithread

Each process is independent, process a problems will not affect process B;

Although threads run independently, threads in a process share the same heap. If a threadout of memoryThen all threads in this process are finished.

So multi process can improve the fault tolerance of the systemfault toleranceThe biggest advantage of multithreading is that the communication between threads is very convenient.

Communication between processes requires additional mechanisms, such as inter process communicationinterprocess communicationIPCOr network delivery, etc.

How to create a thread

There are a lot of concepts mentioned above. Next, let’s look at the specific implementation.

Java is throughjava.lang.ThreadThis class is used to realize the function of multithreading. Let’s take a look at this class first.

As we can see from the document,ThreadClass is direct inheritanceObjectAt the same time, it is also realizedRunnableInterface.

There are also two ways to create threads in the official documents

One way is fromThreadClass, and overriderun()run()Method is the code to be executed by this thread;

Pass at startupnewthisclassCall thestart()Method to start the thread.

How cruel! It's really Ali's technology. This set of multithreaded triple questions almost makes me doubt my life!

The second is to achieveRunnableInterface and implementationrun()run()Method also writes the code to be executed by this thread;

Slightly different is the start thread, which requiresnewA thread, and just created this implementationRunnableInterface class instance, and then callstart()This is actuallyproxy pattern

How cruel! It's really Ali's technology. This set of multithreaded triple questions almost makes me doubt my life!

If the interviewer asks you, is there anything else

  1. realizationCallableInterface
  2. Start a thread through the thread pool.

But in fact, using thread pool to start a thread is also created in one of the first two ways.

I won’t elaborate on these two ways. Let’s look at the first two ways specifically.

Inherit thread class

public class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System. Out. Println ("Xiaoqi 666," + I) ";
        }
    }
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
        for (int i = 0; i < 100; i++) {
            System. Out. Println ("main thread" + I + ": Qijie 666");
        }
    }
}

ad locum,

  • mainFunction is the main thread, the entry of the program, executing the whole program;
  • A new thread is started after the program starts executingmyThread, output “Xiao Qi” in this thread;
  • The main thread executes in parallel and outputs “mainline program I: Qi Jie”.

How cruel! It's really Ali's technology. This set of multithreaded triple questions almost makes me doubt my life!

Take a look at the result. Two threads praise me alternately

How cruel! It's really Ali's technology. This set of multithreaded triple questions almost makes me doubt my life!

Q: Why is it different from what I run?

In multithreading, the result of each run may be different, because we have no legal person to control which thread grabs resources first at what time.

Of course, we can give priority to threadspriorityHowever, high priority can not guarantee that this thread will be executed first. It can only be said that there is a greater probability of preempting resources to execute first.

Implementation of runnable interface

This method is used more.

public class MyRunnable implements Runnable {
    @Override
    public void run() {
        for(int i = 0; i < 100; i++) {
            System. Out. Println ("Xiaoqi 666," + I) ";
        }
    }

    public static void main(String[] args) {
        new Thread(new MyRunnable()).start();

        for(int i = 0; i < 100; i++) {
            System. Out. Println ("main thread" + I + ": Qijie 666");
        }
    }
}

The results were similar

How cruel! It's really Ali's technology. This set of multithreaded triple questions almost makes me doubt my life!

As mentioned earlier, the thread startup mode here is slightly different from that just now, because the newly created class only implements theRunnableInterface, so we also need a thread to “proxy” it, so we need to pass the instance of our new class into a threadproxy pattern。 I’ll talk about this design pattern later.

Summary

Finally, we provide free learning materials on Java architecture, including: spring, Dubbo, mybatis, RPC, source code analysis, high concurrency, high performance, distributed, performance optimization, microservice advanced architecture development, etc. Friends in needClick here for commentsDownload by yourself, hope to help you!

There are also Java core knowledge points + a full range of architects’ learning materials and videos + a big factory interview Treasure + interview template, you can receive + Ali, NetEase, Tencent, Iqiyi, Kwai, Iqiyi, beep, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li, Li Yuan, +Spring, the source code of the interview, and the book is about the real e-book of the Java structure.
How cruel! It's really Ali's technology. This set of multithreaded triple questions almost makes me doubt my life!