Android程序中,线程分为主线程(UI thread)和工作线程(work thread)。我们要遵循单线程模型原则:安卓UI的操作线程不安全,安卓UI的操作必须在主线程进行。
1、多线程任务开发可以通过以下几个方式实现:Handler、AsyncTask。详见:http://blog.csdn.net/qq_29266921/article/details/54893254
2、如果子线程的数据想通知到UI线程中,实现方法:
Activity.runOnUIThread(Runnable)
runOnUiThread(new Runnable(){//更新UI
@Override
public void run() {
publish_time.setText("更新失败");
}
});
view.post(Runnable)或者new Handler().post()
view.post本质上是异步消息处理机制。相对于新建Handler进行处理更加便捷,参考一下源码
public boolean post(Runnable action) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
return attachInfo.mHandler.post(action);
}
// Assume that post will succeed later
ViewRootImpl.getRunQueue().post(action);
return true;
}
post
方法相当于把这个事件添加到了UI 事件队列尾部,保证了在layout结束以后才执行。view.postDelayed(Runnable, long)或者new Handler().postDelayed(Runnable, long)
3.管道流(不常用),管道为两个线程建立一个单向的通道。生产者PipedWriter负责写数据,消费者PipedReader负责读取数据。感觉很繁琐,不想用。
public class PipeExampleActivity extends Activity {
private static final String TAG = "PipeExampleActivity";
private EditText editText;
PipedReader r;
PipedWriter w;
private Thread workerThread;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
r = new PipedReader();
w = new PipedWriter();
try {
w.connect(r);
} catch (IOException e) {
e.printStackTrace();
}
setContentView(R.layout.activity_pipe);
editText = (EditText) findViewById(R.id.edit_text);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
try {
if(count > before) {
w.write(charSequence.subSequence(before, count).toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
workerThread = new Thread(new TextHandlerTask(r));
workerThread.start();
}
@Override
protected void onDestroy() {
super.onDestroy();
workerThread.interrupt();
try {
r.close();
w.close();
} catch (IOException e) {
}
}
private static class TextHandlerTask implements Runnable {
private final PipedReader reader;
public TextHandlerTask(PipedReader reader){
this.reader = reader;
}
@Override
public void run() {
while(!Thread.currentThread().isInterrupted()){
try {
int i;
while((i = reader.read()) != -1){
char c = (char) i;
Log.d(TAG, "char = " + c);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
4.共享内存(不常用,除非存在高并发,例如火车票之类的APP)
synchronized(this) {
while(isConditionFullfilled == false) {
wait();
}
notify();
}
3、4请参考:http://www.tuicool.com/articles/7NZnayB