I would say add a field that indicates the stream needed to run and render, and the number of threads, if the stream number == a stream is required, then it is allowed to start and visualize and increase the required stream field until it reaches its maximum, then go back to 0. Alternatively, you can use one stream for a tick and another for rendering, it might be easier. Here is a sample code:
public Game() {
this.tickThread=new Thread(this::tickLoop());
this.renderThread=new Thread(this::renderLoop());
}
public void tickLoop() {
while(running) {
tick();
}
}
public void renderLoop() {
while(running) {
render();
}
}
Alternatively you can say:
| MyRunnable.java |
public interface MyRunnable
{
public abstract void run(boolean toRender);
}
| MyThread.java |
public class MyThread extends Thread
{
private boolean isRender;
private MyRunnable runnable
public MyThread(boolean isRender,MyRunnable runnable)
{
this.isRender=isRender;
this.runnable=runnable;
}
public void run()
{
this.runnable.run(this.isRender);
}
}
| Game.java |
public class Game extends /*JPanel/Canvas/JFrame/Some other component*/
{
private MyThread tickThread;
private MyThread renderThread;
private boolean running;
public Game()
{
super();
tickThread=new MyThread(this::run);
renderThread=new MyThread(this::run);
}
public void tick()
{
}
public void render()
{
}
public void run(boolean isRender)
{
while(running)
{
if(isRender)
{
this.render();
}
else
{
this.tick();
}
}
}
}
source
share