开发者

How to get rid of this "static method should be acessed in a static way" in java?

I have the following piece of code in a java application

Thread.currentThread().sleep(10000);

However eclipse is showing me the following warning:

The static method sleep(long) from the type Thread should be accessed in a static way

I am very proud of never release code with warnings, and I would like to get rid of this warning (it occurs in two different classes). Do I need to post the entire 开发者_Go百科code?


You call

Thread.sleep(10000);

It always makes the current thread sleep. Even if you did:

Thread t = new Thread(...);
t.start();
t.sleep(10000);

That would still make the current thread sleep for 10 seconds, while leaving the new thread to go on its merry way. This is almost the canonical example for why this warning is important - it's because you're calling a static method as if it were an instance method, which makes it look like it matters what you're calling it on. It doesn't. The value isn't even checked for nullity:

Thread t = null;
t.sleep(10000); // Still sleeps for 10 seconds...

(I'm proud to say I originally filed a feature request for this warning in Eclipse back in June 2002 :)


Thread.sleep(...) (a static method on Thread).

Causes the currently executing thread to sleep ...

It doesn't make sense to tell another thread to sleep: making it static ensures this restriction (albeit "only with a warning").

The code in the post will compile because obj.sm is rewritten by the compiler to T.sm, where sm is a static method on class T and the compile-time type of obj is T: as such it is the static method which is invoked and not an instance method (for a particular Thread), which is what the warning is about.

Happy coding.


Yup, when you look at the doc for sleep() it says "static void sleep(long millis)". The "static" isn't there because of noise in the channel, it means that the method should be addressed Thread.sleep(...) instead of someThreadObject.sleep(...). As a "convenience" you can use the latter form, but it's strongly discouraged.


The way to go is

Thread.sleep(10000);

With the intention, that you can send to sleep only yourself anyways. A real non-static method would imply, that you could send another thread sleeping too.


Just call Thread.sleep(10000), it will cause the current thread to sleep. http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html#sleep(long)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜