"What happens if a thread calls start() twice?"
If this question comes from the first question of the Ali p6 post, can you answer it?
Hi, my name is Mic, a Java programmer who has been working for 14 years.
Regarding this question, it involves the life cycle of the thread. I have organized the complete answer into the interview document of 15W words. You can privately message me to receive it.
Let's take a look at the expert's answer below.
Expert:
In Java, a thread can only call the start() method once, and the second call will throw an IllegalThreadStateException.
A thread itself has a life cycle.
In Java, the life cycle of a thread includes 6 states.
- NEW, the thread is created and has not called start to start
- RUNNABLE, the thread in this state may be running, or it may be waiting for the operating system to schedule and allocate CPU resources in the ready queue.
- BLOCKED, the thread is in lock waiting state
- WAITING, indicating that the thread is in a conditional waiting state, and wakes up when a condition is triggered, such as wait/notify.
- TIMED_WAIT, the same state as WAITING, except that it triggers an additional timeout condition
- TERMINATED, indicating the end of thread execution
When we call the start() method for the first time, the state of the thread may be in a terminated or other state other than the NEW state.
Calling start() again is equivalent to re-running the running thread, which is unreasonable both from the perspective of thread security and from the execution logic of the thread itself.
Therefore, in order to avoid this problem, the running state of the current thread will be judged first when the thread is running.
Summarize
This question is very simple.
It is usually used as a warm-up question during the interview process.
All you need to do is answer the exception message.
A deep understanding of threads is very helpful for our daily development work and problem diagnosis.
Remember to like and subscribe! ! !
Copyright notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated. Please indicate the source forMic带你学架构
!
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) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。