A fan who went to JD.com to interview for 5 years came to me and said:
Mr. Mic, you said that concurrent programming is very important. Sure enough, I was hung up on another concurrent programming interview question today.
I asked him what the problem was and he said: "How to interrupt a running thread?".
I said that many people who have worked for 2 years know this problem~
Well, for this question, let's take a look at the answers of ordinary people and experts.
Ordinary people:
Um. . . . . . . . . . .
Expert:
I will answer this question in several ways.
First of all, threads are a system-level concept. The final execution and scheduling of threads implemented in Java are determined by the operating system. The JVM just wraps the threads at the operating system level.
So when we start a thread through the start method in Java, we just tell the operating system that the thread can be executed, but it is decided by the scheduling algorithm of the operating system that it is finally handed over to the CPU for execution.
Therefore, in theory, to interrupt a running thread at the Java level, it can only be forced to terminate in the same way as the kill command in Linux ends the process.
Therefore, a stop method is provided in Java Thread to forcibly terminate, but this method is unsafe, because it is possible that the task of the thread has not yet been executed, resulting in incorrect running results.
To safely interrupt a running thread, only a hook can be buried inside the thread, and the external program can trigger the thread's interrupt command through this hook.
Therefore, an interrupt() method is provided in Java Thread. This method is used in conjunction with the isInterrupted() method to implement a safe interrupt mechanism.
This implementation method is not a forced interrupt, but tells the running thread that you can stop, but whether you want to interrupt depends on the running thread, so it can ensure the safety of the thread running result.
The above is my understanding of the problem!
Summarize
This question, many small partners who have worked for more than 5 years are not necessarily clear.
What I want to say is that in addition to a lot of growth in the first 3 years of focusing on automated repetitive work like CRUD, the follow-up time is basically doing repetitive work.
It is precisely the 8 hours outside work that separates you from others.
If you think the work is good, remember to like and follow.
Copyright notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated. Reprint please indicate the sourceMic带你学架构
!
If this article is helpful to you, please help to follow and like, your persistence is the driving force for my continuous creation. Welcome to follow the WeChat public account of the same name to get more technical dry goods!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。