当前位置: 代码迷 >> 综合 >> JAVA中创建线程thread.start方法
  详细解决方案

JAVA中创建线程thread.start方法

热度:85   发布时间:2024-01-28 09:27:10.0

java中创建一个新的线程有多种方式,如new Thread,实现runnable,实现callball;但归根结底都是new Thread,重写run方法。

如果调用run方法,则只是使用当前线程调用了一个普通的方法,而不是new Thread执行run方法。

执行Thread.start方法的源码:


public class Thread implements Runnable {//本地方法,注册java方法和jvm方法的映射关系//比如:java中thread的sleep方法,映射的jvm中sleep方法private static native void registerNatives();static {registerNatives();}//thread的start方法public synchronized void start() {/*** This method is not invoked for the main method thread or "system"* group threads created/set up by the VM. Any new functionality added* to this method in the future may have to also be added to the VM.** A zero status value corresponds to state "NEW".*/if (threadStatus != 0)throw new IllegalThreadStateException();/* Notify the group that this thread is about to be started* so that it can be added to the group's list of threads* and the group's unstarted count can be decremented. */group.add(this);boolean started = false;try {//重点是这个start0()方法start0();started = true;} finally {try {if (!started) {group.threadStartFailed(this);}} catch (Throwable ignore) {/* do nothing. If start0 threw a Throwable thenit will be passed up the call stack */}}}//本地静态方法//registerNatives映射关系使用上了//执行jvm中的创建线程方法,在linux系统中执行的是pthread_create方法//直接交给操作系统内核去启动一个线程//内核线程初始化、创建线程完成后,会调用thread.run方法private native void start0();}

总结:

1.new Thread时,会创建本地方法和jvm内核库方法(c++实现)的一个映射关系;

2.调用start方法时,会调用start0方法,这个方法对应jvm的一个内核库方法,执行该jvm方法;

3.jvm创建线程完成后,会使用新创建的线程回调thread.run方法。