Handler的post方法与Runnable

 
  
/**
 *
 * @tips  :将自己线程中的代码段传递到主线程中执行,用post方法就可以把runnable中的代码进行传递了。
 *
 */
public class MainActivity extends Activity {
    TextView valueTv;
    public Handler mHandler;
    private MyThread thread;
    // 定义一个自己的线程
    class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println("线程开始运行");
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    valueTv.setTextColor(Color.RED);
                    valueTv.setTextSize(30);
                    valueTv.setText("从线程中传过来的代码段");
                    System.out.println("执行runnable代码的线程:"+Thread.currentThread().getName());
                }
            };
            //上面代码中的runnable线程体经过post后会直接传送到主线程中执行修改字体的操作。
            //post直接可以把一段代码当做变量一样传递,但是请不要传送耗时操作的代码到主线程中
            mHandler.post(r);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        valueTv = (TextView)findViewById(R.id.vale_textView);
        mHandler = new Handler();
        thread = new MyThread();
        // 启动线程
        thread.start();



        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                System.out.println("-=-=-=>>xianchengid11111 = " + Thread.currentThread().getId());
                ImageUtil.deleteImageFromSDCard(imgPath);
            }
        }, 3000);
    }



}



最后打印如下:
        [java] view plain copy
            07-09 10:47:24.110 17026-17026/com.spd.sinoss I/System.out: -=-=-=>>xianchengid00000 = 1
        07-09 10:47:27.111 17026-17026/com.spd.sinoss I/System.out: -=-=-=>>xianchengid11111 = 1
可以看出来,它们两个程序都是运行在主线程中的。
方法的官方解释是:
The runnable will be run on the thread to which this handler is attached.
        既是说,这个开启的runnable会在这个handler所依附线程中运行,而这个handler是在UI线程中创建的,所以
        自然地依附在主线程中了

猜你喜欢

转载自blog.csdn.net/briup_qiuqiu/article/details/80606953