class threaddemo extends Thread
{
Thread t ;
t=Thread.currentThread();//error(incompatible type. thread cant,t be converted to t)
String s=t.getName();
@Override
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println(i+" "+t.getName());
try
{
Thread.sleep(1000);
} catch (InterruptedException ex)
{
Logger.getLogger(threaddemo.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
答案 0 :(得分:1)
您不能像以下那样进行初始化:
Thread t ;
t=Thread.currentThread(); //error(incompatible type. thread cant,t be converted to t)
如果你不在方法之内。
如果变量是类的字段,则基本上*必须在一行上进行声明和实例化:
Thread t = Thread.currentThread();
*我说基本上是因为这不是严格正确的。您也可以使用构造函数,例如:
class MyClass
{
String str; //declaration
MyClass()
{
str = "hello"; //instantiation
}
}
至少还有一种不常见的方法,我现在不用担心。 This page of Oracle's site描述了它。