2017-09-21 94 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運行?

回答

1

這是一個單獨的線程這裏唯一的事情是這樣的片段:

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

    // Do some IO? 
    longRunningMethod(); 
} 

其他的一切是你的主線程。因此,從內部運行調用的任何內容都在您的新線程中。所以表面創建,銷燬等。是主線程,所以你的「運行」變量應該可能是鎖定保護或易失性的,以確保你不會在不同的線程在錯誤的時間發生錯亂的競爭條件。

在longRunningMethod()完成後,請記住,您不再運行該線程,除非您在其中放置一個循環以保持活動狀態。

相關問題