android应用程序也是单线程程序,主线程为UI线程。
android 线程是非安全的,即不要在子线程中更新 UI。
- public class MasterActivity extends Activity {
- TextView tv = null;
- Button btn = null;
- Handler mHandler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- if(msg.what == 1) {
- tv.setText("update UI is success!");
- btn.setText("update UI is success!");
- }
- super.handleMessage(msg);
- }
- };
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- System.out.println(Thread.currentThread().getName() + ": " + Thread.currentThread().getId());
- tv = (TextView)findViewById(R.id.text);
- btn = (Button)findViewById(R.id.btn);
- btn.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- Thread thread = new Thread(new Runnable() {
- @Override
- public void run() {
- System.out.println(Thread.currentThread().getName() + ": " + Thread.currentThread().getId());
- Message msg = mHandler.obtainMessage();
- msg.what = 1;
- msg.sendToTarget();
- }});
- thread.start();
- }
- });
- }