首先,两个方法都是返回线程ID,但结果是不同的,简单的说
android.os.Process.myTid()是系统级的ID
Thread.currentThread().getId()是Java级的ID
看源码
Android/sdk/sources/android-28/android/os/Process.java
/** * Returns the identifier of the calling thread, which be used with * {@link #setThreadPriority(int, int)}. */ public static final int myTid() { return Os.gettid(); }
Android/sdk/sources/android-28/android/system/Os.java
/** * See <a href="http://man7.org/linux/man-pages/man2/gettid.2.html">gettid(2)</a>. */ public static int gettid() { return Libcore.os.gettid(); }
#include <sys/types.h> pid_t gettid(void);
myTid()是系统给分配的ID,可以使用setThreadPriority()来设置线程优先级。有兴趣可以把注释中的链接打开看看。
Android/sdk/sources/android-28/java/lang/Thread.java
/* * Thread ID */ private long tid; /* For generating thread ID */ private static long threadSeqNumber; public Thread(Runnable target) { init(null, target, "Thread-" + nextThreadNum(), 0); } private void init(ThreadGroup g, Runnable target, String name, long stackSize) { Thread parent = currentThread(); if (g == null) { g = parent.getThreadGroup(); } g.addUnstarted(); this.group = g; this.target = target; this.priority = parent.getPriority(); this.daemon = parent.isDaemon(); setName(name); init2(parent); /* Stash the specified stack size in case the VM cares */ this.stackSize = stackSize; tid = nextThreadID(); } private static synchronized long nextThreadID() { return ++threadSeqNumber; } public long getId() { return tid; }
也就是说Thread.getId() 是 Thread类自己管理的一个静态ID,在调用构造函数时即生成,从1开始递增。
至于为什么会搞两个线程ID,应该是由于Java是跨平台语言,各种操作系统有自己的一套管理线程的方式,而Java这么做可以统一管理。他自己的Thread类中也能实现设置线程优先级等操作。
发表评论