A simple stream of Android crash applications

I found a very peculiar problem when creating a thread launch inside an Android application.

If I have the following class:

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 onCreate (...) method, for example:

 public class MyActivity extends Activity { TroubleThread myThread; @Override public void onCreate(Bundle savedInstanceState) { //.... myThread = new TroubleThread(); myThread.setRunning(true); myThread.start(); } } 

application crashes.

But if I changed the run () method to:

 @Override public void run() { while (running){ //NOTE THE USE OF DIRECT FIELD ACCESS INSTEAD OF METHOD }//end while }//end run 

he stops from crashing.

Even if I solved my problem using locks, notify () and wait (), the question remains:

Why does the application continue to work when using direct access to the field, but does it fail when using the method?

+5
source share

Source: https://habr.com/ru/post/1245539/


All Articles