简体   繁体   中英

What is not running on main thread?

Given the simplified custom view below, what exactly is/isn't running on main thread?

// 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(){
        // ...
    }
}

Is all of CustomView running on a separate thread?

The only thing that is on a separate thread here is this snippet:

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

    // Do some IO?
    longRunningMethod();
}

Everything else is on your main thread. So anything called from inside run is in your new thread. so surface created, destroyed etc.. are main thread so your "running" variable should probably be lock protected or volatile to make sure you don't create a race condition of getting set out of order at wrong time from separate thread.

Also keep in mind after longRunningMethod() completes you are no longer running that thread unless you put a loop in there to keep it alive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM