draw() 函数总是由同一个线程调用。这个相同的线程也调用 mousePressed() 和类似的函数。在 Processing 中,这被称为动画线程——Java 也有类似的想法,称为 EDT。
因此,您不能简单地将绘图移至其他线程。这将导致渲染出现问题 - 例如,动画线程可能正在尝试绘制下一帧,而您的绘图线程仍在尝试绘制前一帧。这是行不通的。
您可以尝试通过让所有辅助线程绘制到 PGraphics 而不是直接调用 Processing 绘制方法来进行自己的多线程屏幕外缓冲。然后,您必须同步所有绘图线程,并且仅在所有这些线程完成后将 PGraphics 绘制到屏幕上(使用动画线程)。
这不是一项特别困难的工作,但它确实涉及对线程如何工作的相当不错的理解,这超出了大多数处理草图的范围。
另外请注意,JavaScript 没有多个线程,因此您对线程执行的任何操作都不会在 JavaScript 模式下工作。
这是一个示例草图,它仅使用动画线程每帧绘制 10000 个随机点。我得到了大约 7 FPS:
PGraphics sharedGraphics;
void setup(){
size(500, 500);
sharedGraphics = createGraphics(500, 500);
}
void draw(){
sharedGraphics.beginDraw();
sharedGraphics.background(0);
for(int i = 0; i < 10000; i++){
sharedGraphics.ellipse(random(500), random(500), 5, 5);
}
sharedGraphics.endDraw();
image(sharedGraphics, 0, 0);
println(frameRate);
}
以下是您可以如何使用多个线程来呈现到 PGraphics:
PGraphics sharedGraphics;
void setup() {
size(500, 500);
sharedGraphics = createGraphics(500, 500);
}
void draw() {
ArrayList<Thread> threads = new ArrayList<Thread>();
sharedGraphics.beginDraw();
sharedGraphics.background(0);
for (int i = 0; i < 100; i++) {
Thread t = new DrawThread();
threads.add(t);
t.start();
}
for (Thread t : threads) {
try {
t.join();
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
sharedGraphics.endDraw();
image(sharedGraphics, 0, 0);
println(frameRate);
}
class DrawThread extends Thread {
public void run() {
for (int i = 0; i < 100; i++) {
sharedGraphics.ellipse(random(500), random(500), 5, 5);
}
}
}
但是,它的性能甚至比单线程模型更差,而且我得到了奇怪的伪影(一些椭圆被填充,另一些没有),这表明 PGraphics 不是线程安全的。这可能取决于您使用的渲染器类型。然后你可以添加一些同步:
class DrawThread extends Thread {
public void run() {
for (int i = 0; i < 100; i++) {
synchronized(sharedGraphics) {
sharedGraphics.ellipse(random(500), random(500), 5, 5);
}
}
}
}
这行得通,但它的性能更差,因为您仍然一次只能使用一个线程访问 PGraphics,并且每次调用 draw() 时都会做很多额外的工作。
您也许可以摆弄它以使其正常工作,但最终结果是它可能不值得。
“有些人在遇到问题时会想“我知道,我会使用多线程”。这不是问题。”