如果你运行程序,你可以看到它打印“调用Run()方法”,当运行被调用时。但if语句中的System.out.println()不会被调用,也不会调用render()方法。
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable {
public static int WIDTH = 300;
public static int HEIGHT = WIDTH / 16*9;
public static int SCALE = 3;
public static String TITLE = "";
private Thread thread;
private boolean running = false;
private JFrame frame;
public void start() {
if(running) return;
thread = new Thread(this);
thread.start();
}
public void stop() {
if(!running) return;
try{
thread.join();
}catch(InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
System.out.println("Run() has been called");
long lastTime = System.nanoTime();
long timer = System.currentTimeMillis();
double ns = 1000000000.0 / 60.0;
double delta = 0;
int ticks = 0;
int fps = 0;
while(running) {
long now = System.nanoTime();
delta += (now-lastTime) / ns;
lastTime = now;
while(delta >= 1) {
tick();
ticks++;
delta--;
}
render();
fps++;
if(System.currentTimeMillis() - timer > 1000) {
timer += 1000;
System.out.println("Fps: " + fps + " Ticks: " + ticks);
fps = 0;
ticks = 0;
}
}
stop();
}
public void tick() {
}
public void render() {
BufferStrategy bs = getBufferStrategy();
if(bs==null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.fillRect(36, 25, 25, 25);
g.dispose();
bs.show();
}
public Game() {
setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
frame = new JFrame();
}
public static void main(String[] args) {
Game game = new Game();
game.frame.setResizable(false);
game.frame.setTitle("SPACE ADAPT PRE-ALPHA 0.001");
game.frame.add(game);
game.frame.pack();
game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.frame.setLocationRelativeTo(null);
game.frame.setVisible(true);
game.start();
}
}
答案 0 :(得分:3)
你永远不会将running
设置为true,那么它就是假的。作为与此问题无关的附注,但大多数swing组件方法都不是线程安全的,因此调用另一个不是Event Dispatch Thread的线程将无法按预期工作。