2015-03-08 214 views
0

我對java很新。非常。就像我基本上從今天開始。我有其他語言的編程知識,如c,c + +,PHP,JavaScript等,但我無法弄清楚這一點。我開始在Youtube上觀看關於如何用Java製作視頻遊戲的教程(來自ChernoProject的視頻),但大約有7集,我遇到了一個問題,我們有我們的窗口,我們畫了一個黑色的矩形,並且該應用程序凍結了我的整個計算機。這裏是我的代碼:Java應用程序凍結

package com.darksun.theonetruemike.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(){ 
     while(running){ 
      update(); 
      render(); 
     } 
    } 

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

} 

我使用Eclipse來使這個項目(高度違揹我的意願),而當我按下Debug按鈕,出現的窗口,我的電腦死機,產生具有強制退出整個計算機。如果可以,請提供幫助,並提前感謝您的幫助!

+0

你怎麼知道它凍結了,它似乎沒有做任何事情。也。你主循環可能會超支,這可能會消耗你的CPU週期... – MadProgrammer 2015-03-08 20:36:41

+0

我知道它凍結,因爲我按下關閉按鈕,它需要大約5分鐘無所事事,然後我不得不強制退出我的電腦 – 2015-03-08 20:38:55

+0

什麼是你試圖用線程來完成? – lacraig2 2015-03-08 20:49:29

回答

0

因爲我有低信譽,我將發佈作爲回答我的意見,儘量不要-rep

我複製你的代碼到NetBeans中,看起來像窗口黑色控制檯,什麼都不會發生,但它不凍結,但JVM正在使用CPU的50%左右

+0

是的,我想通了,這是因爲我的電腦couldn'處理進程的數量。謝謝,但它幫助 – 2016-12-07 00:20:47

+0

我很高興我可以幫助:) – Akos 2016-12-12 09:02:45