When I put the code below in NetBeans, NetBeans gives me a warning next to it saying "Accessing static method sleep".
try {
Thread.currentThread().sleep(2000);
}
catch(InterruptedException ie){
//continue
}
Am I doing something wrong? Should I be calling this differently? I'm not doing anything multi-threaded. I just have a simple main method that which I want to sleep for a while.
Thread.currentThread() returns an instance of the Thread class. When invoking a static method you only want to work on the class itself. So invoking a static method on current thread you will get a warning you are calling the method on an instance.
You would just call Thread.sleep(2000);
It would be equivalent to Thread.currentThread.sleep(2000);
This is important to know because people have been burned doing something like:
Thread a = new Thread(someRunnable);
a.start();
a.sleep(2000); //this will sleep the current thread NOT a.
Edit: So how do we sleep a? You sleep a by writing the sleep invocation within the runnable passed in to the constructor, like:
Runnable someRunnable = new Runnable(){
public void run(){
Thread.sleep(2000);
}
};
When 'a' is started, Thread.currentThread in someRunnable's run method is the 'a' thread instance.
sleep
is static, so you access it with Thread.sleep(2000);
. It affects the current thread.
From the javadoc:
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. The thread does not lose ownership of any monitors.
What that means is that you can't sleep another thread, only the one that the code is in.
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