Android中的混乱多线程

时间:2013-02-18 14:07:51

标签: java android multithreading thread-sleep

这是我的代码:

public class MainActivity extends Activity {
    private TextView view;
    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        view = (TextView) findViewById(R.id.view);
        view.setText("how are you");

        handler.post(r);

        System.out.println("oncreate");
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        System.out.println("onstart");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    Runnable r = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    };
}

activity_main.xml 中,我采用了LinearLayout,其中只有一个TextView。运行程序后,文本字符串“你好吗”将在屏幕上显示为10几秒钟后。但是文本字符串“oncreate”和“onstart”可以立即显示在logcat中。怎么会发生这种情况?在我看来,所有的文本字符串都应该在运行程序后10秒钟内显示出来。

1 个答案:

答案 0 :(得分:0)

这样做的简单方法是:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = (TextView) findViewById(R.id.view);
System.out.println("oncreate");
new Thread(new Runnable() {
        public void run() {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }
         }
}).start();
    view.setText("how are you");

}

此代码将在logcat上立即打印“onstart”和“oncreate”,10秒后将在textview上设置文本...