2017-09-21 40 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()完成后,请记住,您不再运行该线程,除非您在其中放置一个循环以保持活动状态。

相关问题