本帖最后由 翁鹏 于 2012-10-25 12:19 编辑
实现Runnable接口的类只是线程要执行的一个任务,Runnable不是线程。而我们必须把要执行的任务交给线程去执行,Thread类才是线程类,我们把Runnable对象传递给Thread(线程)的构造函数,让线程可以执行里面的任务(run方法中的代码)。Thread类的start方法开启线程,并调用了Runnable对象中的run方法。start方法到底是怎么实现这两个功能的我没有研究过。
你可以去看看start()方法的源代码,start()方法开启线程用到了一个native本地方法。应该和系统有关吧。- 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();
- 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 */
- }
- }
- }
- private native void start0();
- /**
- * If this thread was constructed using a separate
- * <code>Runnable</code> run object, then that
- * <code>Runnable</code> object's <code>run</code> method is called;
- * otherwise, this method does nothing and returns.
- * <p>
- * Subclasses of <code>Thread</code> should override this method.
- *
- * @see #start()
- * @see #stop()
- * @see #Thread(ThreadGroup, Runnable, String)
- */
- @Override
- public void run() {
- if (target != null) {
- target.run();
- }
- }
复制代码 |