对实例初始化感到困惑

时间:2013-10-04 13:25:51

标签: java

我有一个班级,例如:

public class Test {

    private static Thread aThread;
    private static Loopy aLoop;

    public Test() {
    }

    public static void main(String[] args) {

        startUpdate();
        stopUpdate();
        startUpdate();

    }

    public static void startUpdate() {

        aLoop = new Loopy();
        aThread = new Thread(aLoop);

        aThread.start();

    }

    public static void stopUpdate() {

        if (aThread != null) {
            aLoop.finish();
        }
    }
}

使用看似如下的可运行代码:

public class Loopy implements Runnable {

    private static String status = "R";       // Run

    public void run() {

        while (status.equals("R")) {
            // Do Stuff
        }
    }

    public void finish() {
        status = "F";                         // End Run
    }
}

第一次调用startUpdate。

StopUpdate按计划工作。

第二次调用startUpdate导致没有工作,因为状态仍然等于停止的“F”,即使我正在启动一个新的Loopy实例(对我来说)应该具有默认值“R” ”

状态是否在实例之间持续存在,或者我发现了一个我还没有发现的错误?

2 个答案:

答案 0 :(得分:5)

您过度使用了static

Loopy课程中,String statusstatic,因此会在所有Loopy个实例之间共享。

您应该删除status

,使static成为实例变量

另一个注意事项是status也应该是volatile,因为它的状态被许多线程改变而没有同步。

我还建议您也可以在Test实例中创建所有变量/方法(main除外),因为通常最好尽可能避免static

public class Test {

    private Thread aThread;
    private Loopy aLoop;

    public static void main(String[] args) {
        final Test test = new Test();
        test.startUpdate();
        test.stopUpdate();
        test.startUpdate();

    }

    public void startUpdate() {
        aLoop = new Loopy();
        aThread = new Thread(aLoop);
        aThread.start();
    }

    public void stopUpdate() {
        if (aThread != null) {
            aLoop.finish();
        }
    }
}

答案 1 :(得分:0)

我认为状态不应该是静态的

相关问题