多线程源码解析
知道怎么使用之后我们来看看JDK中实现多线程的方式。
先看看Thread类的开头public
class Thread implements Runnable
从此可见,JDK中的Thread类实际上还是实现了Runnable方法的。
接下来是Thread中的run方法
public void run() {
if (target != null) {
target.run();
}
}
terget是一个Runnable类型的变量,在构造方法中被初始化,这也是我们使用Runnable接口的方式
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
接下来我们来看看start方法,里面有一些不懂得暂时不用管他
public synchronized void start() {
if (threadStatus != 0)
throw new IllegalThreadStateException();
group.add(this);
boolean started = false;
try {
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
}
}
}
这里我们看到其调用了start0方法,这个方法是一个native方法,也就是这里使用了系统调用。
按照本节内容查看JDK源代码。