Is it hunger?

I found a piece of code in which the thread seems to be starving. The following is a simplified example. Is this an example of hunger? What is the reason why the thread does not end?

Note. Changing the sleep mode to 1 sometimes leads to completion. Commented Thread.yield () will solve the problem (for me).

public class Foo {

    public static boolean finished = false;

    public static void main(String[] args) {

          Runnable worker = new Runnable() {

                 @Override
                 public void run() {

                      try {
                           Thread.sleep(10);
                      } catch (InterruptedException e) {
                          // TODO Auto-generated catch block
                          e.printStackTrace();
                      }

                      finished = true;
                 }
            };

            new Thread(worker).start();

            while (!finished) {
//          Thread.yield();
        }
    }
}
+1
source share
2 answers

You probably need to get information about the Java memory model. Multithreading is not just the interleaving of threads; it is about the visibility of actions from one thread to another.

concurrency: , , , () . , volatile , - ( , ).

finished - , -, . ,

while (!finished);

if (!finished) while (true);

- , , finished , , , .

, : " ": , , - , .

+6

, . Starvation , . ? "", .

0

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


All Articles