2013-03-21 3 views
0

Pong 게임을 만드는 방법을 보여주는 가이드를 따르고 있습니다. Thread를 생성하고 공을 움직이는 함수를 호출해야하는 부분이 있습니다. android의 스레드가 예상대로 작동하지 않습니다.

내가 만든 코드 :

package com.ozadari.pingpong; 

public class PingPongGame extends Thread { 
private Ball gameBall; 
private PingPongView gameView; 

public PingPongGame(Ball theBall,PingPongView mainView) 
{ 
    this.gameBall = theBall; 
    this.gameView = mainView; 
} 

@Override 
public void run() 
{ 
    while(true) 
    { 
     this.gameBall.moveBall(); 
     this.gameView.postInvalidate(); 

     try 
     { 
      PingPongGame.sleep(5); 

     } 
     catch(InterruptedException e) 
     { 

      e.printStackTrace(); 
     } 

    } 
}} 

이 스레드는 작업이라고하고 있지만, 아무것도 인쇄되지 않습니다. 나는 infinte 루프를 취소하고 루프를 100 번 실행하려고했습니다. 잠시 기다린 후에는 100 회 실행 한 후 화면에 인쇄하지만 중간에 아무 것도 인쇄하지 않습니다.

무엇이 문제입니까? 어떻게 해결할 수 있습니까?

+1

코드에서 아무 것도 인쇄되지 않아야합니다. moveBall()도보고 싶습니다. – tilpner

+0

수면 시간을 1000으로 늘리려고 했습니까? 그러면 변화를 볼 수 있습니까? – WarrenFaith

+0

메인 스레드에서 직접 실행 메소드를 호출하는 것처럼 들리십니까? start를 호출하여 스레드를 스레드로 시작해야합니다. –

답변

1

당신이 게시 한 코드에서 확실하지만 어쨌든, 당신은 핸들러를 사용하고 매초마다과 같이 실행할 수 있습니다 (당신이 원하는에 시간을 변경) :

Handler handler = new Handler(); 
final Runnable r = new Runnable() 
{ 
    public void run() 
     { 
      //do your stuff here 
       handler.postDelayed(this, 1000); 
     } 
}; 

handler.postDelayed(r, 1000); 

http://developer.android.com/reference/android/os/Handler.html

또한 일반 스레드를 사용할 수 있으며 끝에 start를 호출 할 수 있습니다.

Thread thread = new Thread() 
{ 
    @Override 
    public void run() { 
     try { 
      while(true) { 
       sleep(1000); 
       handler.post(r); 
      } 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
    } 
}; 

thread.start(); 
+0

폴 감사합니다!, 문제는 내가 calle thread.run(); thread.start() 대신 ; 네가 보여준대로! 감사합니다. –

+0

다행 당신은 그것을 분류 :) – Paul

관련 문제