线程 Thread Handler

new Thread(new Runnable() {
    @Override
    public void run() {
        Message msg = new Message();
        msg.what = 0;
        myhandler.sendMessage(msg);
    }
}).start();    
public Handler myhandler = new Handler() {
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what) {      //判断标志位
            case 0:
                MakeToast("finished!");
                break;
        }
    }
};

 中断线程,thread_update_view是线程的名字:

if(thread_update_view!=null){
    thread_update_view.interrupt();
    thread_update_view = null;
}

 关于中断,最好就使用上面这个interrupt的方法,因为不会强行中断,但是需要注意:

比如:

thread_cut_music = new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            mediaPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
            myApp.MakeToast("找不到资源");
            int temp = (myApp.getUser_music_playing()+1)%myApp.getUser_music_url_list().size();
            myApp.setUser_music_playing(temp);
            CutMusic();
        }
    }
});

这里面mediaPlayer.prepare()可能会执行很久,如果在这过程中使用了interrupt中断该线程,prepare()还是会继续执行,这时如果抛出错误,那么catch里面的内容会被执行,并不会因为interrupt而取消执行。

所以,很多时候需要这样做。

private class ThreadSafeCut extends Thread {
    public void run() {
        try {
            mediaPlayer.prepare();
            if(isInterrupted()) return;
            if(myApp.getIs_usermusic_playing()){
                mediaPlayer.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
            if(!isInterrupted()){    //如果线程没被中断,则自动切歌
                Log.d(TAG, "run: "+isInterrupted());
                myApp.MakeToast("找不到资源");
                int temp = (myApp.getUser_music_playing()+1)%myApp.getUser_music_url_list().size();
                myApp.setUser_music_playing(temp);
                CutMusic();
            }
        }
    }
}

可以利用isInterrupted()来查看这个线程是否被中断。

在Activity销毁之前,清除Handler所有Message和Runnable;

原文地址:https://www.cnblogs.com/zhaozilongcjiajia/p/10478355.html