我们在子线程使用handler的post方法时,如下:
new Thread(new Runnable() { @Override public void run() { System.out.println("UI线程ID2="+Thread.currentThread().getId()); hh.post(new Runnable() { @Override public void run() { textView2.setText("gaibianle"); System.out.println("UI线程ID3="+Thread.currentThread().getId()); } }) ; } } ).start();post方法里面传入 new Runnable 对象,然后在其下面的run方法中,竟然可以操作UI线程,更改ui,对此不少人有疑惑,不是不能在非UI线程更改UI吗?
答案如下:我们传入的new Runnable ,不是新的线程。而是UI线程。
我们在代码中打印当前的线程:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); textView2= (TextView) findViewById(R.id.texthh); System.out.println("UI线程ID1="+Thread.currentThread().getId()); new Thread(new Runnable() { @Override public void run() { System.out.println("UI线程ID2="+Thread.currentThread().getId()); hh.post(new Runnable() { @Override public void run() { textView2.setText("gaibianle"); System.out.println("UI线程ID3="+Thread.currentThread().getId()); } }) ; } } ).start();结果如下:
08-07 22:09:41.673 30533-30533/com.example.cirleimg I/System.out: UI线程ID1=1
08-07 22:09:41.676 30533-30664/com.example.cirleimg I/System.out: UI线程ID2=25480
08-07 22:09:41.743 30533-30533/com.example.cirleimg I/System.out: UI线程ID3=1
所以,handler的Post方法就是直接操作UI线程。