When a Processing sketch is running there is a single thread that handles all events (mouse click, mouse move, key pressed etc) and rendering the display(i.e. the draw method).
In your code you create a second thread and from that you attempt to render to the display e.g. rect(10,10,width-20,height-20);
this is not permitted. It restriction imposed by the JVM (Java Virtual Machine) which actually executes your program.
Take a step back, here. What are you actually trying to achieve? Threading, particularly at the lowest level managing the threads yourself, is advanced level, and probably isn’t something to consider if it’s all new to you.
I have no idea how the post() suggestion is meant to help you?!
So you would create an off-screen PGraphics object
Update the off-screen graphics in the secondary thread
In draw() use image(…) to display the graphic.
That would be a good way to do it but there are some caveats
Would need a mechanism to prevent draw() attempting to display the graphic at the same time the other thread is updating it. (I would probably use a double buffered image)
In the secondary thread inside the run() method you need to put a delay in the while loop to prevent it hogging the CPU like this.
public void run() {
while (true) {
count++;
displayNumbers();
try {
Thread.sleep(100); // milliseconds
}
catch(InterruptedException e){
}
}
}
I guess that would be an ok solution however there is currently a problem in processing where PGraphics cannot be instanced with FX2D which is currently my fave renderer due to the speed advantage over other renderers, I am open to being persuaded to use an alternative, in which case this could work.
What is it doing though? I assume this isn’t the code you’re talking about? If it’s mainly drawing things, then maxing out a single core isn’t going to be fixed by this. All the renderers are single threaded, so you need to consider a more powerful renderer.
eg. OpenGL
size(200,200,P2D);
On the other hand, if it’s maxing out in non-drawing calculations, then you might get a benefit from threading. Although as @quark points out, a loop without some sort of sleep or other call that causes it to pause for a while will just max out the CPU core for no reason.
I have no idea how @GoToLoop idea is meant to help you. The best way to pass data from one thread into the animation thread is through using one of the blocking queues available inside the core Java libraries. For some reason, Processing people decided not to provide a beginner friendly utility around this. Threading must be the single biggest cause of confusion around here!