I found a very peculiar issue when creating an launching a thread inside an Android app.
If I have the following class thread:
public class TroubleThread extends Thread{
boolean running;
public boolean isRunning() {
return running;
}
public void setRunning(boolean running) {
this.running = running;
}
@Override
public void run() {
while (isRunning()){
}//end while
}//end run
}
and add it somewhere in the Activity's onCreate(...) method like:
public class MyActivity extends Activity {
TroubleThread myThread;
@Override
public void onCreate(Bundle savedInstanceState) {
//....
myThread = new TroubleThread();
myThread.setRunning(true);
myThread.start();
}
}
the app will crash.
But if I change the run() method to:
@Override
public void run() {
while (running){ //NOTE THE USE OF DIRECT FIELD ACCESS INSTEAD OF METHOD
}//end while
}//end run
it stops from crashing.
Even if I solved my problem by using locks, notify() and wait() the question still remains:
Why when using direct access to the field the app continues to work while when using the method it crashes?