我想更有效地运行我的游戏。我想使用两个线程而不是一个线程。现在,我想使用一个while循环来并行运行这两个类。但是,如果我现在开始游戏,则在while循环在第一个线程中停止之前,不会释放第二个线程。 这是我的代码:
public class Game {
public void Game() {
Update update;
Render render;
update.start();
render.start();
}
}
class Update implements Runnable {
private Thread thread;
private boolean running;
@Override
public void run() {
while(running) {
//Update Stuff
}
}
public synchronized void start() {
if(running)
return;
running = true;
thread = new Thread(this);
thread.start();
}
}
class Render implements Runnable {
private Thread thread;
private boolean running;
@Override
public void run() {
while(running) {
//Render Stuff
}
}
public synchronized void start() {
if(running)
return;
running = true;
thread = new Thread(this);
thread.start();
}
}
如何同时启动两个线程?预先感谢。
答案 0 :(得分:0)
类似的事情应该起作用:
public class Game {
volatile boolean running = true;
Thread updateThread;
Thread renderThread;
public void Game() {
}
public void start() {
Update update = new Update(this);
updateThread = new Thread(update);
updateThread.start();
Render render = new Render(this);
renderThread = new Thread(render);
renderThread.start();
}
public void waitForFinish() throws InterruptedException {
updateThread.join();
renderThread.join();
}
boolean isRunning() {
return running;
}
}
class Update implements Runnable {
private final Game game;
Update(Game game) {
this.game = game;
}
@Override
public void run() {
while (game.isRunning()) {
try {
Thread.sleep(1000);
System.out.println("Update");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Render implements Runnable {
private final Game game;
Render(Game game) {
this.game = game;
}
@Override
public void run() {
while (game.isRunning()) {
try {
Thread.sleep(100);
System.out.println("Render");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private void test() throws InterruptedException {
Game game = new Game();
game.start();
game.waitForFinish();
}