我也不完全理解 volatile 和 synchronized 修饰符的作用。但基本上这应该是我从 youtube 系列中学习的游戏的开端,到目前为止它所做的只是启动一个线程,该线程有一个 while 循环,在内部运行方法更新和渲染。事情是除了颜色的设置和矩形的创建之外,我不了解渲染方法中的任何内容。
package game;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
public class Game implements Runnable {
public static Thread Game;
public volatile boolean running = false;
public void start() {
running = true;
Game = new Thread(this);
Game.start();
}
public synchronized void stop() {
running = false;
try {
Game.join();
} catch (InterruptedException e) {
System.out.println("asddsa");
}
}
public void update() {
}
public void render() {
BufferStrategy bs = GameFrame.GraphicsBoard.getBufferStrategy();
if (bs == null) {
GameFrame.GraphicsBoard.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, GameFrame.GraphicsBoard.getWidth(),
GameFrame.GraphicsBoard.getHeight());
g.dispose();
bs.show();
}
public synchronized void run() {
new GameFrame();
while (running) {
update();
render();
}
}
}