thread类的start方法实现
时间: 2023-05-26 17:04:04 浏览: 82
start方法是Thread类的重要方法之一,它的作用是启动一个线程并使它进入“就绪”状态。start方法的实现如下:
1. 首先判断当前线程是否为“新建”状态,只有“新建”状态的线程才能被启动,否则会抛出IllegalThreadStateException异常。
2. 将当前线程加入执行队列中,并调用native方法start0()启动线程。
3. start0()方法会在新的线程中执行run()方法。
代码实现如下:
```
public synchronized void start() {
if (threadStatus != 0)
throw new IllegalThreadStateException();
group.add(this);
boolean started = false;
try {
start0();
started = true;
} finally {
if (!started) {
group.threadUnmap.remove(this);
threadStatus = 0;
}
}
}
```
其中,start0()方法是一个本地方法,由Java虚拟机实现,它的实现方式与操作系统有关。在Windows平台下,start0()方法会使用Win32 API函数CreateThread()创建一个新线程;在Linux平台下,start0()方法会使用pthread_create()函数创建一个新线程。需要注意的是,由于start0()方法是一个本地方法,因此它是不可见的,我们无法在Java中直接调用它。