由于android的UI主界面更新是单线程的,所以在子线程更新界面会提示错误,为此我做了相关实验。可能由于我对主线程和子线程的理解不当,未能实验出子线程更新的提示错误。望大虾帮忙。
我的具体做法为:键一个activity和一个线程thread。在activity中启动thread。我认为thread是子线程,所以在thread中添加了对界面更新的操作,最后没有报错。难道thread不是子线程?
我的具体做法为:键一个activity和一个线程thread。在activity中启动thread。我认为thread是子线程,所以在thread中添加了对界面更新的操作,最后没有报错。难道thread不是子线程?
在需要比较的地方,同样调用Thread.currentThread(),获取当前线程句柄,然后进行比较即可。
public class DrawPicturesActivity extends Activity implements OnClickListener{
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.main);
.
.
.
new Thread(pthread).start();
nThread.start();
.
.
. }
.
.
.
}public class PictureThread implements Runnable{
.
.
.
public PictureThread(DrawPicturesActivity context)
{
tView = (EditText)context.findViewById(R.id.editText1);
} private Handler threadHandler = new Handler(Looper.myLooper())
{
public void handleMessage(Message msg)
{
tView.setText("I can come to this room quietly."); }
}; public void run()
{
Message msg = threadHandler.obtainMessage();
tView.setText("I can come to this room quietly. is that right?");//该操作能成功执行
try
{
Thread.sleep(5000);
}
catch (Exception e)
{
}
//tView.setText("I can come to this room quietly. is that right? second");该操作不能成功执行 threadHandler.sendEmptyMessage(1);
}
}
public class NewThread extends Thread{
.
.
.
public NewThread(DrawPicturesActivity context)
{
tView = (EditText)context.findViewById(R.id.editText1);
}
private Handler threadHandler = new Handler(Looper.myLooper())
{
public void handleMessage(Message msg)
{
tView.setText("I can come to this room loudly.");
}
}; public void run()
{
Message msg = threadHandler.obtainMessage();
try
{
Thread.sleep(3000);
}
catch (Exception e)
{
}
threadHandler.sendEmptyMessage(1);
//tView.setText("The second way to this room!");该操作不能成功执行
}}