I am just working through some examples from my text book, writing the code in Eclipse to figure it out.
This is the code for the method I have a question about:
public void run() {
//Get the lock before entering the loop
synchronized(getClass()) {
for (int i =0; i<N; i++) {
System.out.println(getName() + " is tired");
try{
Thread.currentThread().sleep(DELAY);
} catch (InterruptedException e) {}
System.out.println(getName() + " is rested");
}
On line the line with:
Thread.currentThread().sleep(DELAY)
Eclipse gives a warning: "The static method sleep(long) from the type Thread should be accessed in a static way". Eclipse suggests the following solution:
Thread.currentThread();
Thread.sleep(DELAY);
I don’t understand why it makes a difference (if it really does). Can someone please explain?
sleep()is a static method and causes the current thread to sleep for the specified amount of time. Thus thecurrentThread()call is superfluous, and can potentially be confusing since it almost implies that you could make another thread sleep by using similar code (you can’t).The best way to write that code is simply: