Reputation: 746
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
Upvotes: 2
Views: 866
Reputation: 1500375
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.)
Upvotes: 6