在另一个线程中的一个线程内运行代码 [英] Run Code Inside One Thread In Another

查看:81
本文介绍了在另一个线程中的一个线程内运行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Processing项目(Processing基于Java).我想在另一个线程(主线程)的一个线程内运行代码.

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); 
}

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?

推荐答案

最常见的解决方案是提供状态变量,并使draw()方法根据当前状态绘制 >.

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.

想法是:

  • 主线程(处理中的动画线程)为每帧调用draw(),而draw()方法使用状态变量绘制屏幕.
  • 其他线程可以修改状态,但与绘图无关或像素...
  • 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...

考虑2个示例:

1)简单状态(单个布尔变量)

// 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)更复杂的状态

// 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++;
}

请记住,每秒draw()方法被调用60次(如果使用默认帧速率).每个draw()执行都会修改屏幕(像素)缓冲区.如果要从屏幕上分解不需要的对象,则应使用background(color)开始draw()方法,该方法将清除整个缓冲区.

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.

这篇关于在另一个线程中的一个线程内运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆