Thread.currentThread()
can use to get the currently executing thread. And as I think both of the sleep and yield methods are static because they can't execute sleep or yield on other threads. So by making them static it will sleep or yield only the currently executing thread.
This seems to be working in single processor system, if I callThread.currentThread()
or sleep then there's only the currently running thread, it will return or it will sleep. But in a multicore system, multiple threads can run at once,
So how Thread.currentThread()
or Thread.sleep()
works...?
The method Thread.currentThread()
returns the thread which we are currently running inside. It is simply a way of saying: "Hey give me a reference of the thread that is running me"
Suppose we have four cores and four threads A,B,C and D are running absolutely concurrently, calling this method at the same time, it will return A, B, C and D appropriately based upon the thread we are currently in.
And methods Thread.currentThread().sleep()
or Thread.sleep()
are doing essentially the same job. As per the documentation for currentThread():
public static Thread currentThread()
Returns a reference to the currently executing thread object.
and
public static void sleep(long millis)throws InterruptedException
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.
The documentation is very poor in this case. What Thread.currentThread()
returns is actually the thread where you execute that line of code in. So whether you are in a multi-processor environment or not doesn't matter in this case.
When you have two threads ThreadA
and ThreadB
running completely in parallel and you ask for Thread.currentThread()
in parallel at the same time you will get the corresponding thread where this is executed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With