Author: Flower Gie

WeChat official account: Java development zero to one

preface

In the last series we introduced the basics of multithreading, and you usually understand some of the difference.

“Crouching pit can also enter Dachang” multi-thread these basic interview questions, 80% of small partners on the first question wrong

Today continue to explain the relatively basic theoretical knowledge of multi-threading, if you are a novice or do not know much about multi-threading, do not think about going up on the liver actual combat class, useless, casually out of a bug you can not see what reason, flower GIe strongly recommended to follow this series to finish (manual dog head protection body).

I: yo shout, the dog remaining son today how not at home cultivation, also don’t accompany your girlfriend, and come to the company to write a bug

Dog left son: hey hey, how possible not accompany girlfriend, we every day inseparable

I:…

Dog left son: take advantage of today no one, go, see you in the pit, I want to be honest with you.

The body of the

I: the dog left son, please listen to the first question, daemon thread and user thread have what distinction?

There are two types of threads in Java: Daemon and User. The only difference between the two is that when the virtual machine leaves, the JVM will exit automatically if all threads in the JVM are daemons. However, if there is one or more non-daemon threads, it will not exit.

Me: Yesterday I asked you about notify. Do you know the difference between notify and notifyAll in Java? Or how do we choose which one to use?

Yesterday’s matter actually still remember, you this memory can also ah, I have forgotten.

, notify can’t wake up a specific thread specified (says the Internet, I followed that tell you as to why the back), may cause the signal loss such a question, is it only in a thread waiting at home, and notifyAll will wake all waiting threads, and allow them to compete for the locks, while the efficiency is not high, However, at least one thread is guaranteed to continue execution. If you want to use Notify, you must ensure that the following two conditions are met.

  • A notification only needs to wake up a maximum of one thread.
  • All threads waiting to wake up have the same processing logic. For example, different threads are created using an instance of the Runnable interface, or multiple instances of the same Thread subclass are created by new.

Me: Don’t be proud, these are all appetizers, let me ask you another one, wait is only used in code blocks why?

What? Wait can only be used in code blocks, I didn’t know. That is… Maybe Wait is a neat freak and likes to be alone.

I: you step horse….

Oh… Come to think of it, we can think of it the other way around. If wait does not require that it be in a synchronized block, the following error might occur.

Wait/notify thread-safe queue

class BlockingQueue {
    Queue<String> buffer = new LinkedList<String>();
 
    //
    public void give(String data) {
        buffer.add(data);
        notify();                   // Since someone may be waiting in take!
    }
 
    public String take() throws InterruptedException {
        while (buffer.isEmpty())    // don't use "if" due to spurious wakeups.
            wait();
        return buffer.remove();
    }
}
  1. Consumer A calltake()At this time,buffer.isEmpty()To true;
  2. Consumer A goes into while and it’s callingwait()Method before producer B calls a completegive()(that is, Buffer.add (data) and notify());
  3. And then consumer A callswait(), but missed the producer B callnotify();
  4. If no other producer then calls the give() method, the thread of consumer A waits.

Me: I can’t help but give you a thumbs up for this explanation. Do you know what locks are in Java?

The concept of locking is also available to friends, but should be seen after learning volatile.

Lock this thing to say is very abstract, you can imagine it into the reality of the lock, as for his anti-theft lock, gold lock, or fingerprint lock is not important, even if it is a straw rope, a bicycle, or even a lump that what, can be as a lock. The image of the lock is less important than what it stands for: whoever holds it has independent access to critical resources.

Me: Have you learned anything about thread deadlock?

A deadlock is a state in which two or more threads are blocked indefinitely because they are competing for resources and are waiting for a resource to be released.

As shown in the figure, thread A holds resource 2 and thread B holds resource 1. They both want to apply for each other’s resource at the same time, so the two threads will wait for each other to enter A deadlock state.

Me: Do you know the four conditions necessary to form a deadlock?

What we don’t know, here’s a list for you.

  1. Mutual exclusion: Threads (processes) are exclusive to allocated resources, which means that only one process can occupy the resource at any one time.
  2. Request and hold condition: When a thread (process) is blocked by a request for a resource, it holds on to the acquired resource.
  3. Not deprived condition: the thread (process) has acquired the resource before the end of use can not be forcibly deprived by other threads, only after the use of its own resources to release.
  4. Loop waiting condition: When a deadlock occurs, the waiting thread (process) must form a loop, the loop causes a permanent jam.

Me: Since you know the conditions for deadlock formation, surely you know how to avoid it?

If you want to avoid deadlocks, you need to break any of the four necessary conditions.

  1. Break the mutex: This path is blocked because we use locks to make them mutex in the first place.
  2. Break request and hold condition: claim all resources at once.
  3. Destroy not deprived condition: the possession thread can try to apply for other resources, if it can not apply, can take the initiative to release its possession of resources.
  4. Waiting condition for breaking cycle: apply for resources in a certain order, and release resources in reverse order.

I: this wave answer of good, last night is not secretly prepared. Please continue to listen to the question, the context switch, you know?

Please respect me, please call the dog later.

When it comes to context switching, we need to know what a context is. To put it simply, a context is the contents of CPU registers and program counters at a given point in time.

Expanding: Each thread has a program counter (which records the next instruction to be executed), a set of registers (which holds the current thread’s work variables), and a stack (which records the execution history, where each frame holds a procedure that was called but not returned).

Registers: Registers are the CPU’s internal memory, which stores tasks that have been, are, and will be performed. They are small but fast, as opposed to the relatively slow RAM main memory outside the CPU.

Program counter: A program counter is a special register that indicates where the instruction sequence CPU is currently executing. It stores the location where an instruction is being executed or where an instruction will next be executed.

It means that after the execution of the current task, the CPU will save its state before switching to the next task, so that it can continue to execute when the task is switched back to the next time. The context switch from saving to reloading is a context switch.

If it is not clear enough, you can understand it in the following three steps.

  1. Suspend a process, storing its CPU state (context) in memory;
  2. Retrieves the context of the next process in memory and restores the process in the CPU’s registers;
  3. Restore the process by jumping to the location that the program counter points to, where the code was executing when the process was interrupted.

I: speak of good detail, suddenly good heart, that context switch will bring what problem?

After reading the above introduction, we should have a feeling that in the case of high concurrency, frequent context switching will cause the system to execute serially, and the running speed will be greatly reduced.

  • Direct consumption: This includes CPU registers that need to be saved and loaded, and system scheduler code that needs to be executed.
  • Indirect consumption: CPU in order to accelerate the speed of execution, the common data cached, but when a context switch (that is, the CPU to perform different thread code), the cached content originally very much did not use value, therefore the CPU will to cache, it also cause the thread is scheduled to run after the first start the speed will be slow.

Expand: In order to avoid the overhead of frequent context switching, the thread scheduler sets a minimum execution time for each thread that is scheduled to reduce the number of context switches, thus improving performance, but the obvious disadvantage is that it can slow down the response time.

Me: Can you tell me what volatile is?

No, no, today is tired to death we house, the old need to rest, tomorrow we fight again.

conclusion

Multi-threading knowledge is huge and involves many aspects. Especially for those who have just come into contact with multi-threading, it is very difficult for them to understand such concepts as lock and context. To truly master all the knowledge involved in each problem, they need to dig into the knowledge involved in each problem. Wait /notify is how the producer consumer model works, how the Thread is scheduled, how the Java code is executed by the CPU, and more importantly, how the Thread starts and stops the Thread, and how the Thread communicates.

Giegie will gradually lead you to master these flowers, some big knowledge points will be taken out for a single explanation, I hope you continue to pay attention to the holiday, do not make samples, continue liver.

Keep your eyes on the ground

The above is the whole content of this issue, if there is a mistake, please comment, thank you very much. I’m Giegie. Feel free to leave a comment if you have any questions. We’ll see you at 🦮 next time.

The article is constantly updated, you can search on WeChat”
Java development zero to one“The first time to read, will continue to update the Java interview and all kinds of knowledge points, interested partners welcome to pay attention to, learn together, together ha 🐮.

If you think this article is useful to you, thank brother for liking, commenting or forwarding this article, because this will be the motivation for me to produce more good articles. Thank you!