为什么该线程不起作用? [英] Why this thread doesn't work?

查看:104
本文介绍了为什么该线程不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了这段代码来尝试在Android上运行线程,但是它不起作用.

I wrote this code to try threads on Android, but it doesn't work.

   @Override
   public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Thread t = new Thread() {
            @Override public void run() {
                            int i = 0;
                while(true) {
                                 i += 5;
                                 if(i == 1000000)
                                       break;
                            }
            }
        };
    t.run();
   }

我有一些GUI,当线程正常工作(i <1000000)时,GUI冻结.但是,当线程完成时(i == 1000000),一切正常. 怎么了?

I have some GUI and when thread works (i < 1000000), GUI freezes. But when thread is done (i == 1000000) everything works fine. What's wrong?

//对不起,我的英语

推荐答案

您正在调用t.run(),这意味着您正在运行UI线程中的所有代码,而无需启动新线程.

You're calling t.run() which means you're running all the code in the UI thread without starting a new thread.

您应该调用t.start(),这将启动一个新线程并在该新线程内的run方法中执行代码.

You should call t.start() which will instead start a new thread and execute the code in the run method within that new thread.

(我还建议实现Runnable,然后将Runnable传递给新的Thread构造函数,而不是覆盖run,这只是关注点分离的问题.它不会改变行为在这里,但这是对IMO的一种较清晰的思考方式.)

(I'd also recommend implementing Runnable and then passing the Runnable to a new Thread constructor rather than overriding run, just as a matter of separation of concerns. It won't change the behaviour here, but it's a cleaner way of thinking about it IMO.)

这篇关于为什么该线程不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆