import java.io.*;
interface car
{
void prints();
}
class TestInterface implements car
{
public void prints()
{
System.out.println("falali");
}
public static void main(String[] args)
{
TestInterface test=new TestInterface();

}
}
public class InvokeInterface
{ public void carname(car ming)
{
ming.prints();
}
public static void main(String[] args)
{
InvokeInterface invokeinterface=new InvokeInterface();
exthread xian=new exthread();
xian.start();
TestInterface face=xian.getinstance();


invokeinterface.carname(face);

}
}
class exthread extends Thread
{TestInterface testinterface=null;
public void run()
{
testinterface=new TestInterface();
System.out.print("thread is running");
System.out.println(testinterface);
}
public TestInterface getinstance()
{

System.out.print("testinterface instance");
System.out.println(testinterface);
return testinterface;

}
}运行结果testinterface instancenull
Exception in thread "main" java.lang.NullPointerException
        at InvokeInterface.carname(InvokeInterface.java:24)
        at InvokeInterface.main(InvokeInterface.java:34)
thread is runningTestInterface@765291 为什么会有这个异常啊,真不是理解,
invokeinterface.carname(face);这句怎么没有效果,应该打印出falali我的思路是这样的,定义实现接口,在另一个类中调用接口
让实现接口的类在我定义的那个线程运行,在调用接口类中调用接口,为什么不行啊恳求各位大侠解答
谢谢

解决方案 »

  1.   

    public void run()
    {
    testinterface=new TestInterface();
    System.out.print("thread is running");
    System.out.println(testinterface);
    }testinterface=new TestInterface()是在线程里面赋值 ,赋值前是nullTestInterface face=xian.getinstance();可能在线程启动之前,所以取回null
      

  2.   

    ...  ...
    InvokeInterface invokeinterface=new InvokeInterface();
    exthread xian=new exthread();xian.setPriority(6);xian.start();
    ...  ...
      

  3.   

    xian.start();

    Thread.currentThread().sleep(1); //让主线程休眠TestInterface face = xian.getinstance();就可以了
      

  4.   

    明白了,谢谢interpb(曾曾胡) ( :yuzl32(Hello!有酒醉)