2014-04-05 1 views
0

그래서 저는 지금 막 자바를 배우기 시작했으며 YouTube에서 비디오 자습서를 따르고 있습니다. 이 코드를 실행하려고하면 실행되지만 내 컴퓨터가 느려지고 잠시 후에 모든 것이 고정됩니다. 그게 뭐가 잘못 되었 니? 나는 이것이 관련이 있는지도 모른다. 그러나 나는 리눅스 머신에서 이것을 실행하고있다.내 프로그램이 내 컴퓨터를 사용할 수없는 속도로 늦추는 이유

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(); 

} 
} 
+5

Canvas를 최대 속도로 업데이트하면 다른 많은 것들 중에서 Graphics 객체를 가져오고 릴리스하기 때문에. javax.swing을 살펴 보시기 바랍니다. Timer. – EJP

답변

-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()은 그리 정확하지 않다고 생각합니다. 정확한 타이밍을 얻으려면 다른 방법을 사용해야 할 수도 있습니다.

+0

GUI와 절전 모드()는 섞이지 않습니다. – EJP

+0

@ EJP 정보를 제공해 주셔서 감사합니다. UI 스레드가 아니라 별도의 스레드에서 잠자기가 호출되기 때문에 여기에 적용되지만 확실하지 않습니다. 따라서 EDT를 차단하지 않습니다. –

+0

'render()'메쏘드의 코드는 EDT에서 * 호출되고 있다고 가정합니다. – EJP

관련 문제