Occurs before the rules in the Java Memory Model

I am currently studying a parallel program exam and do not understand why the output of this program is 43. Why x = y + 1is it executed before t.start()? I must also explain what happens - before I use the rules.

If I understand the rule of order of the program (every action in the thread happens before each action in this thread that comes later in the order of the program) t.start()must be executed before x = y + 1, so that thread t copies the variable x, which will be equal to 1.

public class HappensBefore {

static int x = 0;
static int y = 42;

public static void main(String[] args) {
    x = 1;
    Thread t = new Thread() {
        public void run() {
            y = x;
            System.out.println(y);
        };
    };
    t.start();
    x = y + 1;
}
+4
source share
5 answers

According to JMM :

start() - .

x y - , x - y , hb (x, y).

:

, t, t - , , t.

- JMM. , , , , .

:

t.start(); hb x = y + 1;//

t.start(); hb y = x;// -

, x = y + 1; y = x; ( JMM).

" ?". ... asnwer. Runtime , JMM.

, , ( ). , . , ... , JMM ...

+3

, no volatile, , . .

, t.start() x = y + 1. , x = y + 1. main().

+8

( - , )

, . , : , :

Thread t = new Thread() {...};
t.start();

JVM .

, , "1". , "0", , A B - .

, .

:

, , - . - , .

, .
.
, , , . : x = y + 1:

t.start(); 
x = y + 1;

, , , , t, .

, .
, , , .
. x = y + 1; , , .

+4

t.start x = y + 1, , run() x = y + 1.

, - , 1 43.

+2

I would like to add that the code of the main method works in the main thread, and Thread t does not block the execution of Main in your example. Therefore, a line x = y + 1can run faster than the body of Thread t (as @davidxxx already pointed out).

You can observe other behavior if added t.join()aftert.start():

t.start();
t.join();

In this situation, the main thread will wait for Thread t to complete , and the output will be 1.

+1
source

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


All Articles