一:看程序
package com.example.testuithread;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// button1添加动画操作
Button button1 = (Button) findViewById(R.id.button1);
TranslateAnimation animation = new TranslateAnimation(0, 150, 0, 0);
animation.setRepeatCount(3);
animation.setDuration(2000);
button1.setAnimation(animation);
// 为button2添加一个点击事件,实现一个阻塞
Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
System.out.println("线程开始执行----线程id = "
+ Thread.currentThread().getId());
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 线程阻塞优化方案1:post方法
v.post(new Runnable() {
@Override
public void run() {
System.out.println("post执行---线程id = "
+ Thread.currentThread().getId());
int sum = 10;
TextView view = (TextView) v;
view.setText("" + sum);
}
});
}
}).start();
System.out.println("线程执行结束----线程id = "+Thread.currentThread().getId());
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
二:post方法
//线程阻塞优化方案1:post方法
v.post(new Runnable() {
@Override
public void run() {
int sum = 10;
TextView view = (TextView) v;
view.setText("" + sum);
}
});
三:后台日志
说明post方法,执行内容放到UI主线程执行。