Akinkunle Allen
Akinkunle Allen

Reputation: 1309

Run Code Inside One Thread In Another

I am writing a Processing project (Processing is based on Java). I want to run the code inside one thread in another thread (the main thread).

//This method runs in the main thread
public void draw() {

}

//This is a callback that runs in a separate thread
void addTuioObject(TuioObject tobj) {
  rect(0, 0, 20, 10); 
}

The rect(0,0,20,10) does not run in the main thread (it is supposed to draw a rectangle on the screen). I suppose this is because it runs in a separate thread. How would I make this code run in the main thread?

Upvotes: 0

Views: 83

Answers (2)

przemek hertel
przemek hertel

Reputation: 4014

Most common solution is to provide state variable and make draw() method to draw according to current state.

State variable may be as simple as single primitive type (boolean for example) or complex object.

Idea is that:

  • main thread (animation thread in processing) calls draw() for each frame, and draw() method uses state variable to paint screen.
  • other thread can modify state, but has nothing to do with drawing or pixels...

Consider 2 examples:

1) simple state (single boolean variable)

// state variable
private boolean shouldPaint;

void draw() {
    background(0);

    fill(200);
    rect(10, 10, 30, 30);

    if (shouldPaint) {
        rect(50, 10, 30, 30);
    }
}

// called in other thread
someMethod() {
    shouldPaint = !shouldPaint;
}

2) more complex state

// state variable
private PVector[] vectors = new PVector[5];
private int index = 0;

void draw() {
    background(0);
    fill(200);

    for (PVector v : vectors) {
        if (v != null) {
            rect(v.x, v.y, 10, 10);
        }
    }

}

// called by other thread
void someMethod() {
    if (index >= vectors.length) {
        index = 0;
    }

    // vector for current index value
    PVector v = vectors[index];

    if (v == null) {
        vectors[index] = new PVector(index * 20, index * 20);
    } else {
        vectors[index].add(new PVector(30, 0));
    }

    index++;
}

Remember that draw() method is called 60 times per second (if default frame rate). Each draw() execution modifies screen (pixel) buffer. If you want to disapper unwanted objects from screen you should start draw() method with background(color) that clears whole buffer.

Upvotes: 1

Christian Frommeyer
Christian Frommeyer

Reputation: 1420

There are several ways to do this. Depending on what you actually want to achieve. If you're working with awt or swing your drawing code should actually not run in the main thread but in the awt thread instead. You can dispatch work to that thread for example using SwingUtils. If you really want to execute the code in another thread (e.g. main) you need to make sure that the target thread will be able to pickup new work e.g. from a queue.

Upvotes: 0

Related Questions