accessing a variable inside a Runnable implementation instance?

edited February 2017 in Questions about Code

Hi all, i've a question. I'm doing some experiment about implementing runnable classes to be able to run process in parallel to the main loop. But i would like to have some vizualization about what is going on. In this case i've a variable who represent the percentage, but i can't access it from outside.

I know i could just point an external variable, but i would like to avoid it. Is forbidden in general to access variables inside this kind of classes?

Thank you, here the code:

Thread t1;

void setup(){
 t1 = new Thread(new myClass(round(random(50, 100))));
 t1.start();
}

void draw(){
  background(200);
  text("percentage: " + t1.progress, 10,10);  // this don't works
}

class myClass implements Runnable {

  int range;
  public float progress;

  myClass(int input) {
    this.range = input;
  }

  //@Override
    public void run() {
    for (int i = 0; i< range; i++)
    {
      println("running");
      progress = map(i, 0, range, 0, 100);
      delay(100);
    }
  }
}
Tagged:

Answers

  • Answer ✓
    MyClass c1;
    
    void setup() {
      c1 = new myClass( round(random(50, 100)) );
      new Thread(c1).start();
    }
    
    void draw(){
      getSurface.setTitle("percentage: " + c1.progress);
    }
    
  • Thank you, so basically my error was definig it as a thread, that still was working but that variable was just defined in my class that was an implementation of it?

  • edited February 2017

    Correct! It doesn't matter whether a class instance is used or not as a Thread argument.
    In order to access its members, we need its reference regardless. :>

  • Actually this can simplify my life so much. Next step would be to understand the best way to have a callback like situation. I was thinking to set an internal boolan and keep checking it, is there something better?

Sign In or Register to comment.