Long press to scan the code , Share the technology stack that Internet companies focus on
1. Several ways to create threads ：
- Realization Runnable Interface
- Inherit Thread class .
- Thread pool creates threads .
- Having a return value Callable Create thread
- Other ways to create Timer Timer.
- Other creation methods ： Anonymous inner class ,lambda expression .
2. Why to achieve Runnable Interface ratio inheritance Thread Class implementation thread is better ？
- 1. First , Let's think about the architecture of the code , actually ,Runnable There's only one run() Method , It defines what needs to be done , under these circumstances , Realized Runnable And Thread Class decoupling ,Thread Class is responsible for thread startup and property settings , Clear responsibilities .
- 2. Performance angle ：Thread Each time you need to maintain the life cycle of the thread , From creation to destruction .Runnable It can be used in thread pool , Reduce performance overhead .
- 3. Code extensibility ：Java Language does not support double inheritance , If our class once inherited Thread class , Then it has no way to inherit other classes , thus , If this class needs to inherit other classes in the future to realize some functional expansion , It can't do it , It's equivalent to limiting the code's future extensibility .
3. How to stop the thread correctly ？ Why? volatile The stop method of the marker bit is wrong ？
- Usually , We don't manually stop a thread , It allows threads to run to the end , And let it stop naturally . But there are still a lot of special situations that require us to stop threads early , such as ： The user suddenly shut down the program , Or program running error restart, etc .
- under these circumstances , Threads that are about to stop are still valuable in many business scenarios . In particular, we want to write a very robust , Programs that can handle various scenarios safely , It is very important to stop the thread correctly . however Java It doesn't offer ease of use , Ability to stop threads directly and safely .
- about Java for , The most correct way to stop a thread is to use interrupt. but interrupt It only notifies the stopped thread . And for stopped threads , It has full autonomy , It can either choose to stop immediately , You can also choose to stop after a period of time , You can also choose not to stop at all .
- Thread.sleep(1000000); have access to thread.interrupt(); Interrupt . After triggering , The thread in sleep is interrupted , Then the thread can feel the interrupt signal , And will throw out a InterruptedException abnormal , At the same time clear the interrupt signal , Set the interrupt flag bit to false. In this way, you don't have to worry about a long sleep when the thread doesn't feel the interruption , Because even if the thread is still sleeping , Still able to respond to interrupt notifications , And throw an exception .
- For exceptions thrown , It should be reported to the top , Instead of swallowing up . The exception is left to the caller . You can also do it in catch Statement to interrupt the thread again . Because if the thread is interrupted during sleep , The interrupt signal will be cleared automatically . If you add an interrupt manually at this time , Interrupt signals can still be captured . In this way, the subsequent execution method can still detect that an interrupt has occurred here , You can do something about it , The whole thread can exit normally .
- volatile This method, in some special cases , For example, the thread is blocked for a long time , You can't feel the interruption in time , therefore volatile It's not a comprehensive way to stop threads .
4. How threads are in 6 Transition between states ？
- Thread 6 States , It's like living things from birth to growing up 、 The process of death is the same , Threads also have their own lifecycles , stay Java In the life cycle of threads in, there are 6 States .
- New（ New creation ）
- Runnable（ Can run ）
- Blocked（ Blocked ）
- Waiting（ wait for ）
- Timed Waiting（ Time wait for ）
- Terminated（ Terminated ）
- If you want to determine the current state of the thread , Can pass getState() Method , And the thread can only be in 1 States .
- State flow ：
5. What's the total 3 Thread like security ？
- 1. Running result error :i++ problem .
- 2. Publishing and initialization lead to thread safety issues
- 3. The question of activity ： There are three of the most typical , They are deadlock 、 Live lock and hunger .
6. Which scenarios require additional attention to thread safety ？
- 1. Access shared variables or resources , Typical scenarios have access to properties of shared objects , visit static Static variables , Access shared cache , wait .
- 2. Timing dependent operations ： If the correctness of our operation depends on timing , But in the case of multithreading, we can't guarantee that the execution order is consistent with our expectation , At this point, thread safety issues will occur
- 3. There is a binding relationship between different data ： The third thread safety scenario that we need to pay attention to is that there is a binding relationship between different data . occasionally , The difference between us is in groups of data , There is a corresponding or binding relationship between them , The most typical is IP And port number . Sometimes we change IP, It is often necessary to change the port number at the same time , If you don't bind these two operations together , There may be a separate replacement IP Or port number , At this time, if the information has been released to the public , It is possible for the information acquiring party to obtain a wrong IP Binding to port , At this point, there is a thread safety problem . under these circumstances , We also need to guarantee the atomicity of operations .
- 4. The other party did not claim to be thread safe ： The fourth notable scenario is when we use other classes , If the other party does not claim to be thread safe , In this case, multithreading concurrent operations are performed on other classes , Thread safety problems may occur . for instance , For example, we define ArrayList, It's not thread safe in itself , If more than one thread at this time ArrayList Read concurrently / Write , Then there may be thread safety problems , Causing data errors , And the responsibility is not ArrayList, Because it's not concurrent security itself .
7. Why multithreading brings performance problems ？
- Scheduling overhead
- Context switch
- Cache invalidation
- Collaboration cost
8. What's better about using thread pools than creating threads manually ？
- 1. Thread pool can solve the system overhead problem of thread life cycle , At the same time, it can speed up the response . Because threads in the thread pool can be reused , We only use a small number of threads to perform a large number of tasks , This greatly reduces the thread life cycle overhead . And threads are not usually created temporarily after receiving tasks , It's created to be ready to perform tasks , This eliminates the delay caused by thread creation , Improved response speed , Enhanced user experience .
- 2. Thread pools can co-ordinate memory and CPU Use , Avoid misuse of resources . The thread pool can flexibly control the number of threads according to the configuration and the number of tasks , Create when you don't have enough , Recycle when it's too much , Avoid memory overflow caused by too many threads , Or too few threads lead to CPU Waste of resources , A perfect balance has been achieved .
- 3. Thread pool can manage resources in a unified way . For example, thread pool can manage task queue and thread uniformly , You can start or end tasks in unison , It's more convenient than a single thread to process tasks one by one 、 Easier to manage , It's also good for statistics , For example, we can easily count the number of tasks that have been performed .
This article is a platform of operation tools such as blog group sending one article and multiple sending OpenWrite Release