所以我刚开始学习java,我正在关注youtube上的视频教程。我正在尝试运行此代码并运行,但它会降低我的计算机速度,然后在不到一秒钟后冻结所有内容。这有什么问题?我也不知道这是否相关,但我目前正在linux机器上运行它。
package com.matt.rain;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable{
private static final long serialVersionUID = 1L;
public static int width = 300;
public static int height = width / 16 * 9;
public static int scale = 3;
private Thread thread;
private JFrame frame;
private boolean running = false;
public Game() {
Dimension size = new Dimension(width * scale, height * scale);
setPreferredSize(size);
frame = new JFrame();
}
public synchronized void start() {
running = true;
thread = new Thread(this, "Display");
thread.start();
}
public synchronized void stop() {
running = false;
try{
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run(){
int x = 1;
while (running == true){
System.out.println("Running..."+ x);
update();
render();
x = x + 1;
}
}
public void update(){
}
public void render(){
BufferStrategy bs = getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
g.dispose();
bs.show();
}
public static void main(String[] args){
Game game = new Game();
game.frame.setResizable(false);
game.frame.setTitle("Rain");
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 :(得分:-1)
您可以在run()中的while循环中使用sleep()
来解决问题。
while (running == true){
// System.out.println("Running..."+ x);
try{Thread.sleep(50);}catch(Exception e){}
update();
render();
x = x + 1;
}
添加sleep()
将允许其他线程与您的程序一起使用,因此不会导致您的计算机停止响应。
尽管如此,我认为sleep()
不是很准确。为了准确计时,您可能必须使用其他方法。