Frage

So, the following, very basic example of threading isn't compiling if i remove the import statement. However, earlier I didn't have to import the Thread class. Has anyone been through this, please assist me.

import java.lang.Thread;
class Test {
 public static void main(String args[]) {
  Thread t = Thread.currentThread();

  System.out.println("current thread is "+t);

  t.setName("amar");
  System.out.println("after name change "+t);

  try {
   for(int n=5;n>0;n--) {
    System.out.println(n);
    Thread.sleep(1000);
   }
  }catch(InterruptedException e) {
   System.out.println("main interrupted");
  }
 }
}
War es hilfreich?

Lösung

You should not need to import any class in java.lang. The class in java.lang are normally available to be used without an explicit import.

"A compilation unit automatically has access to all types declared in its package and also automatically imports all of the public types declared in the predefined package java.lang." - JLS Chapter 7.

The only cases where it may be necessary to explicitly import a java.lang class are when you have declared another class with the same name as a java.lang class. In some circumstances, that class may take precedence over the class in java.lang, forcing you to either import the java.lang class, or use its fully qualified name.

It is a good idea to avoid declaring classes with the same names as commonly used Java library classes, especially those in java.lang.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top