public class Threadtest2 extends Thread
{
class MyThread extends Thread
{
String message;
MyThread(String str)
{
message=str;
}
public void run()
{
for(int i=0;i<3;i++)
System.out.println(message+""+getPriority());
}
};
public static void main(String arg[])
{
Thread t1=new MyThread("T1");
Thread t2=new MyThread("T2");
Thread t3=new MyThread("T3");
setPriority(Thread.MIN_PRIORITY);
start();
        setPriority(Thread.MAX_PRIORITY);
start();
setPriority(Thread.MAX_PRIORITY);
start();
}};
如上程序,为什么在实例化内部类时会提示static方法无法调用非static方法

解决方案 »

  1.   

    当然不能了,声明内类的时候要是不加static,内部类就跟not-static成员变量一样,static函数当然不能调用了
    Thread t1=new MyThread("T1");
    Thread t2=new MyThread("T2");
    Thread t3=new MyThread("T3");
    上面3句得这样写:
    Threadtest2 tt = new Threadtest2();
    Thread t1=tt.new MyThread("T1");
    Thread t2=tt.new MyThread("T2");
    Thread t3=tt.new MyThread("T3");
    或者把MyThread声明为static的。
    后面的也不对:
    setPriority(Thread.MIN_PRIORITY);
    start();
            setPriority(Thread.MAX_PRIORITY);
    start();
    setPriority(Thread.MAX_PRIORITY);
    start();这些都是non-static函数,得建立一个Threadtest2的对象才能调用。
      

  2.   

    问题并不是出在 MyThread 这个内部类的实例化,而是出在 setPriority()、start() 这些方法的调用。你在 main() 中调用这两个方法,就是“static方法无法调用非static方法”喽,因为 main() 是 Threadtest2 中的静态方法,而 setPriority() 是 Threadtest2 中的非静态方法。看楼主的程序,好像本意应该是:    t1.setPriority(Thread.MIN_PRIORITY);
        t1.start();
        t2.setPriority(Thread.MIN_PRIORITY);
        t2.start();
        t3.setPriority(Thread.MIN_PRIORITY);
        t3.start();而且,Threadtest2 没有必要 extends Thread。
      

  3.   

    Sorry, 我上面的回贴还是有问题。索性,把程序改成下面的样子吧,别用什么“内部类”了:public class Threadtest2 {    public static void main(String arg[]) {
            Thread t1 = new MyThread("T1");
            Thread t2 = new MyThread("T2");
            Thread t3 = new MyThread("T3");
            t1.setPriority(Thread.MIN_PRIORITY);
            t1.start();
            t2.setPriority(Thread.MAX_PRIORITY);
            t2.start();
            t3.setPriority(Thread.MAX_PRIORITY);
            t3.start();
        }}class MyThread extends Thread {
        String message;    MyThread(String str) {
            message = str;
        }    public void run() {
            for (int i = 0; i < 3; i++)
                System.out.println(message + "" + getPriority());
        }
    }
      

  4.   

    to maquan('ma:kju)类static成员函数能直接用类的not-static内部类建立对象吗,你编译下程序就知道了
      

  5.   

    TO liye9903():不好意思,最近回帖有点毛躁,没实战,仅凭直觉就回贴了,回过之后总感觉不妥,拿 Eclipse 跑了一遍,才发现有问题。赶紧再回帖补正,不过还是被你抓到了,hehe你说的是对的,如果一定要用内部类的话,是应该搞个 outer class instance 出来,然后通过这个 instance 创建 inner class instance。
      

  6.   

    to maquan我是跑了一遍才回的,hehe