2017-09-21 6 views
0

아래의 단순화 된 사용자 정의보기가 주어지면 주 스레드에서 정확히 실행되고 있지 않습니까?메인 스레드에서 실행되지 않는 항목은 무엇입니까?

// MainActivity 
protected void onCreate(Bundle bundle) { 
    // ... 
    CustomView customView = new CustomView(this); 
    setContentView(customView); 
    customView.setOnTouchListener((v, event) -> { 
     customView.setPoint(event.getX(), event.getY()); 
    }); 
} 


public class CustomView extends SurfaceView implements SurfaceHolder.Callback, Runnable { 
    protected Thread thread; 
    private boolean running; 
    private int x; 
    private int y; 

    public CustomView(Context context) { 
     super(context); 
     thread = new Thread(this); 
    } 

    public void run() { 
     // Get SurfaceHolder -> Canvas 
     // clear canvas 
     // draw circle at point <x, y> 

     // Do some IO? 
     longRunningMethod(); 
    } 

    public void surfaceCreated(SurfaceHolder holder) { 
     running = true; 
     thread.start(); 
    } 

    public void surfaceDestroyed(SurfaceHolder holder) { 
     running = false; 
    } 

    public void setPoint(int x, int y) { 
     this.x = x; 
     this.y = y; 
     run(); 
    } 

    private void longRunningMethod(){ 
     // ... 
    } 
} 

모두 CustomView은 별도의 스레드에서 실행됩니까? 다른

public void run() { 
    // Get SurfaceHolder -> Canvas 
    // clear canvas 
    // draw circle at point <x, y> 

    // Do some IO? 
    longRunningMethod(); 
} 

모두가 메인 스레드에 : 여기에 별도의 스레드에

답변

1

유일한 것은이 조각입니다. 내부에서 호출 된 모든 것이 새 스레드에 있습니다. 그래서 표면 생성, 파괴 등. 메인 스레드 그래서 "실행"변수는 아마도 보호 또는 휘발성이 있어야합니다 경쟁 조건을 만들지 않도록 주문 잘못된 순서로 잘못된 스레드에서 별도의 스레드.

longRunningMethod()가 완료된 후에도 루프를 유지하지 않으면 스레드를 실행하지 않는 것이 좋습니다.