Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

android - Why this thread doesn't work?

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();
   }

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?

// Sorry for my english

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

(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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...