进程有自己的独立地址空间,每启动一个进程,系统就会为它分配地址空间,建立数据表来维护代码段、堆栈段和数据段,这种操作非常昂贵。而线程是共享进程中的数据的,使用相同的地址空间,因此 CPU 切换一个线程的花费远比进程要小很多,同时创建一个线程的开销也比进程要小很多,线程的上下文切换的性能消耗要小于进程。
/** * start方法将导致this thread开始执行。由JVM调用this thread的run方法。 * Causes this thread to begin execution; the Java Virtual Machine * calls the <code>run</code> method of this thread. * <p> * 结果是 调用start方法的当前线程 和 执行run方法的另一个线程 同时运行。 * The result is that two threads are running concurrently: the * current thread (which returns from the call to the * <code>start</code> method) and the other thread (which executes its * <code>run</code> method). * <p> * 多次启动线程永远不合法。 特别是,线程一旦完成执行就不会重新启动。 * It is never legal to start a thread more than once. * In particular, a thread may not be restarted once it has completed * execution. * * @exception IllegalThreadStateException if the thread was already * started. * @see #run() * @see #stop() */ publicclassThreadimplementsRunnable{ /* Make sure registerNatives is the first thing <clinit> does. */ privatestaticnativevoidregisterNatives(); static { registerNatives(); } //start方法用synchronized修饰,为同步方法 publicsynchronizedvoidstart(){ /** * 对于由VM创建/设置的main方法线程或“system”组线程,不会调用此方法。 * 未来添加到此方法的任何新功能可能也必须添加到VM中。 * 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. * status=0 代表是 status 是 "NEW"。 * A zero status value corresponds to state "NEW". */ if (threadStatus != 0) thrownew 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(); started = true; } finally { try { if (!started) { group.threadStartFailed(this); } } catch (Throwable ignore) { /* do nothing. If start0 threw a Throwable then it will be passed up the call stack */ } } } //native方法,JVM创建并启动线程,并调用run方法 privatenativevoidstart0();