Run Code Inside One Thread In Another

痴心易碎 提交于 2019-12-12 06:06:29

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/27202449/run-code-inside-one-thread-in-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!