Java 我是否需要显式导入 Thread 类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22125055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:46:11  来源:igfitidea点击:

Do I need to import the Thread class explicitly?

javamultithreadingcompiler-errors

提问by tphobe9312

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 语句,则以下非常基本的线程示例不会编译。但是,之前我不必导入 Thread 类。有没有人经历过这个,请帮助我。

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");
  }
 }
}

采纳答案by Stephen C

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

您不需要在java.lang. 中的类java.lang通常无需显式导入即可使用。

"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.

编译单元可以自动访问其包中声明的所有类型,并自动导入预定义包中声明的所有公共类型java.lang” - JLS 第 7 章

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

唯一可能需要显式导入java.lang类的情况是当您声明了另一个与类同名的java.lang类时。在某些情况下,班可以优先于类java.lang,迫使你要么导入java.lang类,或者使用其全名。

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

最好避免声明与常用 Java 库类同名的类,尤其是java.lang.