引用同一包中的类中的值

时间:2013-10-16 22:05:24

标签: java

我有两个班级,maintimex。我想在timex类中显示变量的值,但我总是得到答案0.

public class mainaxe {

    public static void main (String arg[]) {
        timex n = new timex();

        int n2 = timex.a;
        n.timedel();
        for(int i=0; i<20; i++) {
            System.out.println("the time is :" + n2);

            try {
                Thread.sleep(1000);
            }

            catch (InterruptedException e) {}
        }
    }
}

这是我的timex课程:

public class timex extends Thread{
    public static int a;

    public int timedel(){
        for(int i=0; i<200; i++) {
            try {
                Thread.sleep(1000);
                a = a + 5;
            }
            catch (InterruptedException e){}

            // start();
        }
        return a;
    }
}

我想从timex类中获取值,并在main类中使用它来每1秒打印一次值。

2 个答案:

答案 0 :(得分:1)

如果你想要一个多线程程序,那么在扩展Thread的类中,声明一个完全相同的方法:

@Override
public void run () {
    // in here, put the code your other thread will run
}

现在,在您创建此类的新对象后:

timex n = new timex();

你必须像这样开始这个线程:

n.start();

这会导致对象开始在新线程中运行其run方法。让你的主线程调用n中的其他方法将不会对新线程做任何事情;主线程调用的任何其他方法都将在主线程中执行。因此,您无法通过函数调用与新线程进行通信。您必须通过其他方式执行此操作,例如您尝试使用变量a

答案 1 :(得分:1)

我想你需要类似的东西,

Mainaxe.java

package mainaxe;

public class Mainaxe {

    public static void main(String arg[]) {
        Timex n = new Timex();
        n.start();
//        int n2 = Timex.a;
//        n.timedel();
        for (int i = 0; i < 20; i++) {
            System.out.println("the time is :" + Timex.a);

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
        }
    }
}

Timex.java

package mainaxe;

public class Timex extends Thread {

    public static int a;

    public Timex() {
        super();
    }

    @Override
    public void run() {
        timedel();
    }

    public int timedel() {
        for (int i = 0; i < 200; i++) {
            try {
                Thread.sleep(1000);
                a = a + 5;
            } catch (InterruptedException e) {
            }

            // start();
        }
        return a;
    }
}