Android程序中,线程分为主线程(UI thread)和工作线程(work thread)。
我们要遵循单线程模型原则:UI操作非线程安全,且必须在UI thread进行。
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.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
新闻热点
疑难解答