0

I am wondering if it is possible in Java to to something like this.

class Running extends Thread {

    private int value;

    public void run() {
        while (true) {
            do stuff;
        }
    }

    public int getValue() {
        return value;
    }
}

public static void main(String[] args){
    Running runner = new Running();
    runner.start();
    int runnerValue = runner.getValue(); // Will I ever get the value?
}

[Edit]

I'm would also like to know if this is recommended or not?

[Edit2]

I'm aware that the value can get screwed up if it is changed in the run() method. The case I was more interested in is actually

private final int VALUE = 100;

Sorry about the ambiguity.

4

3 に答える 3

3

runner.start() will execute your run method in a seperate thread and continue to the next line immediately. runnerValue will then be assigned the value in your class, which will be 0, unless:

  • your run method is changing the value of value
  • AND it has had time to do it (which is very unlikely because starting the thread will probably take too long to allow that to happen)
  • AND you get lucky and can see that change from the main thread - you don't use any form of synchronization to read value in the main thread so there is no guarantee that you could see such a change.
于 2012-11-30T11:18:30.940 に答える
2

From pure program perspective, the code is ok, and you will get a value.

But from logic perspective, the code is bad. runner.getValue() is called immediately after runner.start(). Suppose runner would do something to calculate a value, and getValue() is executed in main thread. So when getValue() is executed in main thread, it's not certain what runner thread is going, so getValue() would return a value that's not you want.

于 2012-11-30T11:23:28.900 に答える
2

I recommend trying it, but what I think is that the following will happen:

  1. The thread will be created and start running.
  2. The main program will get the value, but the thread will still be running.

If you need to wait until some business logic is done, you should use synchronization between the 2 threads. The 1st thread should call a wait method, and the 2nd thread should call notify method upon completion, so the 1st thread is notified.

于 2012-11-30T11:24:27.433 に答える