Android中只有2种类型的线程:MainThread(主线程) 和 WorkerThread。
MainThread 又叫 UI线程,Android应用程序中所有UI相关的代码都是运行在主线程中的,除了MainThread之外的其它所有线程都叫 WorkerThread。
在主线程MainThread中可以启动其它线程(WorkerThread)做一些事情。
MainThread 和 WorkerThread 的关系:
a. Android所有UI相关的代码都是运行在主线程(MainThread)中的;
b. WorkerThread 从原则上来讲是不允许操作UI的(即操作主线程中的UI对象);
c. 但是有部分特殊的UI组件可以在WorkerThread中进行操作,比如:ProgressBar。
public class MainActivity extends Activity
{
private TextView textView;
private Button button;
private ProgressBar progressBar;
@Override
public void onCreate(...)
{
textView = (TextView)findViewById(R.id.textView1);
button = (Button)findViewById(R.id.button1);
progressBar = (ProgressBar)findViewById(R.id.progressBar1);
button.setOnClickListener(new OnClickListener() {
public void onClick(...) {
Thread thread = new MyThread();
thread.start();
}
});
}
/**
* 内部WorkerThread类:MyThread
*/
class MyThread extends Thread {
@Override
public void run() {
// 这里试图在WorkerThread中操作UI,但是这是不允许的
textView.setText("看我改变了,但是这是不可能的。");
// 但是 ProgressBar 是可以的
for(int i = 1; i <= 100; i++) {
try {
Thread.sleep(100);
} catch(Exception e) {
}
// 这里的进度条可以正常工作
progressBar.setProgress(progressBar.getProgress() + 1);
}
}
}
}