日期:2014-05-20  浏览次数:20800 次

一个高深的多线程问题—— 多线程中的多态机制
线程thread类中的start方法是如何调用到实现runnable接口的类中的run方法的?
我查看了jvm的源代码,但是还是没有找到答案,欢迎大家各抒己见咯!

------解决方案--------------------
Java code

public Thread() {
    this(null, null, newName());
}
public Thread(Runnable runnable) {
    this(null, runnable, newName());
}
public Thread(ThreadGroup group, Runnable runnable, String threadName) {
    super();
    if (threadName==null) throw new NullPointerException();
    this.name = threadName;        // We avoid the public API 'setName', since it does redundant work (checkAccess)
    this.runnable = runnable;    // No API available here, so just direct access to inst. var.
    Thread currentThread  = currentThread();

    this.isDaemon = currentThread.isDaemon(); // We avoid the public API 'setDaemon', since it does redundant work (checkAccess)

    if (group == null) {
        SecurityManager currentManager = System.getSecurityManager();
         // if there is a security manager...
        if (currentManager != null)
            // Ask SecurityManager for ThreadGroup
            group = currentManager.getThreadGroup();
    }
    if (group == null)
        // Same group as Thread that created us
        group = currentThread.getThreadGroup();

    initialize(false, group, currentThread);

    setPriority(currentThread.getPriority());    // In this case we can call the public API according to the spec - 20.20.10
}

public void run() {
    if (runnable != null) {
        runnable.run();
    }
}

------解决方案--------------------
看了下,是调用了native方法,这不是多态,是用了JNI
------解决方案--------------------
Java code

public synchronized void start() {
     synchronized(lock) {
         if (started) {
             // K0341 = Thread is already started
             throw new IllegalThreadStateException(com.ibm.oti.util.Msg.getString("K0341"));
         }
         boolean success = false;
         threadGroup.add(this);
        try {
             startImpl();
             success = true;
         } finally {
             if (!success) {
                  threadGroup.remove(this);
             }
         }
    }
 }
private native void startImpl();