在java中创建一个线程, new Thread对象, 并调用它的start()方法, 这是每一个java程序员都知道的事.
在linux C中创建一个线程, 使用pthread_create(&thread, NULL, thread_get_str, NULL)函数, 这是每一个linux C程序员都知道的事.
我们不禁要问,在android中, java线程和c线程到底有没有关系,如果有,到底是怎么样的?
下面开始神秘的dalvik线程创建之旅:
Thread thread = new Thread();
thread.start();
//Thread.java
package java.lang;
public class Thread implements Runnable {
...
public synchronized void start() {
checkNotStarted();
hasBeenStarted = true;
VMThread.create(this, stackSize);
}
...
}
//VMThread.java
package java.lang;
class VMThread {
...
native static void create(Thread t, long stackSize);
...
}
下面进入VMThread.java通过JNI对应的C++文件, java_lang_VMThread.cpp
https://android.googlesource.com/platform/dalvik.git/+/android-4.2.2_r1/vm/native/java_lang_VMThread.cpp
/*
* java.lang.VMThread
*/
static void Dalvik_java_lang_VMThread_create(const u4* args, JValue* pResult)
{
Object* threadObj = (Object*) args[0];
s8 stackSize = GET_ARG_LONG(args, 1);
/* copying collector will pin threadObj for us since it was an argument */
dvmCreateInterpThread(threadObj, (int) stackSize);
RETURN_VOID();
}
进入http://osxr.org/android/source/dalvik/vm/Thread.cpp
//Thread.cpp
bool dvmCreateInterpThread(Object* threadObj, int reqStackSize)
{
...
int cc = pthread_create(&threadHandle, &threadAttr, interpThreadStart, newThread);
...
}
到这里我们就可以清晰的得出结论, android dalvik其实就是通过Linux C的pthread_create实现的线程创建.
refer:
http://www.eoeandroid.com/blog-21517-3026.html?_dsign=30613b5b