线程的底层分析
一、创建线程的方式
- 继承Thread类
- 实现Runnable接口
- 实现Callable接口
- 线程池创建
注:其实底层都是通过new Thread线程来创建
二、线程的生命周期
public enum State {/*** Thread state for a thread which has not yet started.*/NEW,/*** Thread state for a runnable thread. A thread in the runnable* state is executing in the Java virtual machine but it may* be waiting for other resources from the operating system* such as processor.*/RUNNABLE,/*** Thread state for a thread blocked waiting for a monitor lock.* A thread in the blocked state is waiting for a monitor lock* to enter a synchronized block/method or* reenter a synchronized block/method after calling* {@link Object#wait() Object.wait}.*/BLOCKED,/*** Thread state for a waiting thread.* A thread is in the waiting state due to calling one of the* following methods:* <ul>* <li>{@link Object#wait() Object.wait} with no timeout</li>* <li>{@link #join() Thread.join} with no timeout</li>* <li>{@link LockSupport#park() LockSupport.park}</li>* </ul>** <p>A thread in the waiting state is waiting for another thread to* perform a particular action.** For example, a thread that has called <tt>Object.wait()</tt>* on an object is waiting for another thread to call* <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on* that object. A thread that has called <tt>Thread.join()</tt>* is waiting for a specified thread to terminate.*/WAITING,/*** Thread state for a waiting thread with a specified waiting time.* A thread is in the timed waiting state due to calling one of* the following methods with a specified positive waiting time:* <ul>* <li>{@link #sleep Thread.sleep}</li>* <li>{@link Object#wait(long) Object.wait} with timeout</li>* <li>{@link #join(long) Thread.join} with timeout</li>* <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>* <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>* </ul>*/TIMED_WAITING,/*** Thread state for a terminated thread.* The thread has completed execution.*/TERMINATED;}
- NEW:创建一个线程
RUNNABLE:就绪状态,等待获取操作系统资源
- 调用了Object的wait方法后,其他线程调用了notify或者notifyAll方法重新进入就绪状态
- 其他线程调用了LockSupport的unPark方法
BLOCKED:阻塞状态
- 线程进入synchronized修饰的方法或者代码块,
- 其他线程释放锁重新进入synchronized修饰的方法或者代码块
- 调用了Object的wait方法
WAITING:等待状态
- 在没有超时的情况下调用了Object的wait方法
- 在没有超时的情况下调用了Thread的join方法
- 调用LockSupport的park方法
TIMED_WAITING:超时等待状态
- 调用Thread的sleep方法
- 超时调用了Object的wait()方法
- 超时调用了Thread的join方法
- 调用LockSupport的parkNanos方法
- 调用LockSupport的parkUntil方法
- TERMINATED:终止状态
三、线程的创建以及启动流程
思考:线程执行为什么不能直接调用run()方法,而要调用start()方法?
- 使用new Thread()创建一个线程,然后调用start()方法进行java层面的线程启动
- 接着会调用带native的本地方法start0()方法,去调用jvm中的JVM_StartThread方法进行线程创建与启动
- 然后C++底层会根据不同操作系统平台调用创建操作系统内核线程并启动
总结:new Thread()对象后,调用start方法,会映射到jvm中创建OS thread线程,然后jvm底层会调用底层操作系统内核库的pthread_create方法创建线程
