I have simple Activity
that calls AsyncTask
, so I print some id\'s regarding Proces
and Thread
:
From onCr
Very interesting question by the OP and I decided to dig (love open source).
The short answer is: they're different because they're different, because they were never meant to be the same.
Process.myTid()
is the linux thread IDThread.getId()
is a simple sequential long
number.But the short answer is boring, so let's explore where the answer comes from (links in the answer points to the relevant source codes).
In Process.myTid(), you'll see that is simply calls from Os.gettid() that in itself calls a native method on Libcore for that method is below:
public static int gettid() { return Libcore.os.gettid(); }
furthermore the docs for Os.gettid();
you'll find a link to Linux Programmer's Manual
gettid() returns the caller's thread ID (TID). In a single-threaded process, the thread ID is equal to the process ID (PID, as returned by getpid(2)). In a multithreaded process, all threads have the same PID, but each one has a unique TID.
Process.myTid()
returns the thread ID as given by the Linux kernel.On the other hand Thread.getId() is simply returning a long
. This long is assigned during init(...)
as tid = nextThreadId();. Then the last piece of this puzzle, below is the code for nextThreadId()
/* For generating thread ID */
private static long threadSeqNumber;
private static synchronized long More ...nextThreadID() {
return ++threadSeqNumber;
}
Thread.getId()
is simply a "java layer" static long being auto-increment for each thread.