一、实现线程之间通信
方式一
/**
* 线程1往线程2传递数据
*/
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btn(View v) throws InterruptedException {
MyThread2 myThread2=new MyThread2();
myThread2.start();
Thread.sleep(1000);
MyThread1 myThread1=new MyThread1();
myThread1.start();
}
class MyThread1 extends Thread{
@SuppressLint("HandlerLeak")
@Override
public void run() {
super.run();
handler2.sendEmptyMessage(3);
}
}
Handler handler2;
class MyThread2 extends Thread{
@SuppressLint("HandlerLeak")
@Override
public void run() {
super.run();
Looper.prepare();
handler2=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
System.out.println(Thread.currentThread()+" "+msg.what);
}
};
Looper.loop();
}
}
}
方式二:
/**
* 使用HandlerThread 的looper方式实现线程1往线程2传递数据
*/
public class HandlerDemoActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_handler_demo);
handlerThread = new HandlerThread("my-thread");
handlerThread.start();
}
MyThread2 myThread2 = null;
public void btn(View v) throws InterruptedException {
myThread2 = new MyThread2();
myThread2.start();
Thread.sleep(1000);
MyThread1 myThread1 = new MyThread1();
myThread1.start();
}
class MyThread1 extends Thread {
@Override
public void run() {
super.run();
handler2.sendEmptyMessage(3);
}
}
HandlerThread handlerThread;
Handler handler2;
class MyThread2 extends Thread {
@Override
public void run() {
super.run();
handler2 = new Handler(handlerThread.getLooper()) {
public void handleMessage(Message msg) {
System.out.println(Thread.currentThread() + " "
+ msg.what);
};
};
}
}
}
android中更新UI的几种方式
1、handler.sendMessage()
2、handler.post(Runnable r)
3、runOnUIThread();
4、View.post(Runnable r)
从源码分析实现原理就是用的handler的方式。