Processing 处理:将绘图循环运行到独立线程中

Processing 处理:将绘图循环运行到独立线程中,processing,java-threads,Processing,Java Threads,问题 我注意到draw()周期被事件中断。 在以下示例中,圆圈动画将在鼠标单击时停止,直到细化函数()结束 void setup(){ size(800, 600); background(#818B95); frameRate(30); } void draw(){ background(#818B95); //simple animation fill(0,116,217); circle(circle_x,

问题

我注意到
draw()
周期被事件中断。 在以下示例中,圆圈动画将在鼠标单击时停止,直到
细化函数()结束

void setup(){
  
  size(800, 600);
  background(#818B95);
  frameRate(30);
}

void draw(){  
  
    background(#818B95);  
    
    //simple animation 
    fill(0,116,217);  
    circle(circle_x, 200, 50);
    
    circle_x += animation_speed;
    if(circle_x>800){ circle_x = 0; }
}

void mouseClicked() {
  
  elaborating_function();
}

void elaborating_function(){
  println("elaboration start");
  delay(1000);
  println("elaboration end");
}
当然,运行精化而不停止动画的简单解决方案可以是
线程(“精化函数”)

但我的问题是:是否可以将draw循环运行到一个独立的线程中

解决方案

我找到了一个可能的解决方案,将我的问题颠倒过来,创建一个与
draw
one平行的“独立循环”。在此周期内,可以运行任何函数,并且不会干扰绘图执行。用户触发的每个事件只需设置一个特定变量,即可在循环内激活(一次或多次)功能

int circle_x = 0;
int animation_speed = 5;

boolean call_elaborating_function = false;

void setup(){
  
  size(800, 600);
  background(#818B95);
  frameRate(30);
  
  IndependentCycle independentCycle = new IndependentCycle();
  independentCycle.setFrequency(1);
  new Thread(independentCycle).start();
}

void draw(){  
  
    background(#818B95);  
    
    //simple animation 
    fill(0,116,217);  
    circle(circle_x, 200, 50);
    
    circle_x += animation_speed;
    if(circle_x>800){ circle_x = 0; }
}

public class IndependentCycle implements Runnable{
  
  private int frequency; //execution per seconds
  
  public IndependentCycle(){
    
    frequency = 0;
  }
  
  public void setFrequency(int frequency){
    this.frequency = 1000/frequency;
    println(this.frequency);
  }
  
  public void run(){
    
    while(true){
      print(".");
      delay(this.frequency);
          
      //DO STUFF HERE
      //WITH IF EVENT == ture IN ORDER TO RUN JUST ONCE !!
      if(call_elaborating_function){
        call_elaborating_function = false;
        elaborating_function();
      }
    }
  }
}

void mouseClicked() {
  
  call_elaborating_function = true;
}

void elaborating_function(){
  println("elaboration start");
  delay(1000);
  println("elaboration end");
}

据我所知,加工有自己的特点

您提出的线程
细化函数()的解决方案非常好。
如果您需要更多的控制,您可以有一个基本类,它
实现Runnable
。当这个线程并行运行时,处理的主动画线程应该沿着它运行,不会暂停渲染

这个选项听起来比试图搞乱处理的
AnimationThread
简单得多,而且可能必须处理意外行为。
您试图实现的实际目标是什么?

我曾尝试实现一个可运行类,以按照您的建议运行我的细化函数(),但它的行为与中断绘图周期的行为相同。我相信这是由于用户的事件在程序执行过程中触发了一些中断。无论如何,我已经通过运行另一个独立的线程周期并将事件作为唯一的任务来更新该周期内操作的布尔变量触发器,扭转了这个问题。这有点复杂,但很有效。这听起来像是一个明智的解决方案(使用布尔值来“消除”状态以触发函数)。(我想指出的一点是:
frequency=0;
。如果在没有设置frequency>0的情况下意外调用实例,您可能希望使用不同的默认值以避免被零除)做得很好!