Java Reference
In-Depth Information
(Your output may be in a different order.)
Inside main() method: main
Inside run() method: First Thread
Inside run() method: Second Thread
Two different threads call the Thread.currentThread() method inside the run() method of the CurrentThread
class. The method returns the reference of the thread executing the call. The program simply prints the name of the
thread that is executing. It is interesting to note that when you called the Thread.currentThread() method inside the
main() method, a thread named main executed the code. When you run a class, the JVM starts a thread named main ,
which is responsible for executing the main() method.
Letting a Thread Sleep
The Thread class contains a static sleep() method, which makes a thread sleep for a specified duration. It accepts
a timeout as an argument. You can specify the timeout in milliseconds, or milliseconds and nanoseconds. The thread
that executes this method sleeps for the specified amount of time. A sleeping thread is not scheduled by the operating
system scheduler to receive the CPU time. If a thread has the ownership of an object's monitor lock before it goes to
sleep, it continues to hold those monitor locks. The sleep() method throws a java.lang.InterruptedException and
your code should be ready to handle it. Listing 6-11 demonstrates the use of the Thread.sleep() method.
Listing 6-11. A Sleeping Thread
// LetMeSleep.java
package com.jdojo.threads;
public class LetMeSleep {
public static void main(String[] args) {
try {
System.out.println("I am going to sleep for 5 seconds.");
Thread.sleep(5000); // The "main" thread will sleep
System.out.println("I woke up.");
}
catch(InterruptedException e) {
System.out.println("Someone interrupted me in my sleep.");
}
System.out.println("I am done.");
}
}
I am going to sleep for 5 seconds.
I woke up.
I am done.
 
Search WWH ::




Custom Search