上一篇为大家介绍了关于Looper的简单知识,本篇我们介绍一下多线程的并发处理,我们知道Handler通过sendMessage()发送的消息,首先发送给了Looper,存入Looper的消息栈,之后从新发送给Handler对象,Handler对象通过handMessage()方法处理消息。这里就很容易出现空指针异常,下面我们就一起看一下这段代码:
public class MainActivity extends Activity { class Mythread extends Thread{ private Handler handler; private Looper looper; @Override public void run() { Looper.prepare();//创建一个Looper对象 looper = Looper.myLooper(); handler = new Handler(){ @Override public void handleMessage(Message msg) { System.out.println("子线程:"+Thread.currentThread()); } }; Looper.loop();//通过这个方法循环处理方法 } }; private Mythread thread; private Handler secondHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); thread = new Mythread(); thread.start(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } thread.handler.sendEmptyMessage(1);//在子线程中处理 secondHandler = new Handler(thread.looper){ @Override public void handleMessage(Message msg) { System.out.println(msg); } }; secondHandler.sendEmptyMessage(1); } }
这是就会出现空指针异常,因为当我们的SecondHandler创建时,如果thread.looper对象还未创建,就会出现这个异常。那如何防止这个异常呢?谷歌在设计Android时已经为我们考虑到了这一点,这里我们将使用HandlerThread来处理这种多线程并发的问题。
/** * 使用HandlerThread处理多线程并发处理时出现空指针问题 */ public class SecondActivity extends Activity { private HandlerThread handlerThread; private Handler handler; private TextView text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //创建一个TextView text = new TextView(this); text.setText("Helloword"); setContentView(text); //创建一个Handler的线程对象 handlerThread = new HandlerThread("handler thread");//为当前的线程起一个名字 handlerThread.start();//启动线程 handler = new Handler(handlerThread.getLooper()){ @Override public void handleMessage(Message msg) { System.out.println("current:"+Thread.currentThread()); } }; handler.sendEmptyMessage(1); } }
时间: 2024-10-18 19:02:20