E.g. method public static void sleep(long millis). This method causes current thread to sleep, but how does it know, which thread is current? Static methods are object-independent and belong to class, so how does this mechanism work?
- @Downvoter, comment your action, pleaseLies– Lies2013-02-19 11:57:38 +00:00Commented Feb 19, 2013 at 11:57
5 Answers
This method causes current thread to sleep, but how does it know, which thread is current?
The current thread is managed by the underlying operating system (or the threading system). The underlying (system dependant) thread implementation provides a handle to the current thread:
In case of POSIX threads, there is the API call pthread_self() which returns the thread ID of the currently executing thread. You can think of
Thread.currentThread()eventually calling this C function and wrap the thread ID in a JavaThreadobject which is then returned.In case of MS Windows, there is the API call GetCurrentThread() which returns the Windows Handle of the currently executing thread. Again, you can think of
Thread.currentThread()eventually calling this C function and wrap the Handle in a JavaThreadobject which is returned.
6 Comments
currentThread() work if it static and belongs to class, not to concrete Thread object?native methods are special. They have access beyond the Java API.
In this case, to the current thread. You can't use this method to put another thread to sleep - the other thread will have to do this by itself (but you can send it a message, obviously).
2 Comments
It means your current thread will go in sleep mode for a perticlar time. Ex: if i will write Thread.sleep(1000) thread will go to sleep state for 1000 miliseconds. We use this menthod mainly to interchange between the thread.In short, it will give chance to another thread for execution.
1 Comment
The current thread is the one actually executing the piece of code. As simple as that.
For instance:
public static void main(String[] args) { Runnable r = new Runnable() { @Override public void run() { System.out.println("Before sleeping!"); Thread.sleep(10000); System.out.println("After sleeping!"); } } Thread t1 = new Thread(r); Thread t2 = new Thread(r); System.out.println("Main thread!"); } May output something like:
Before sleeping! // t1 Main thread! // main Before sleeping! // t2 After sleeping! // t1 After sleeping! // t2