Created
June 28, 2021 06:36
-
-
Save tcheburator/00afbb691a843a51315e46c9b7953dc3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package empty; | |
import java.util.concurrent.atomic.AtomicInteger; | |
public class Foo { | |
int x = 0; | |
volatile int y = 0; | |
public static void main(String[] args) throws InterruptedException { | |
AtomicInteger counter = new AtomicInteger(0); | |
for (int i = 0; i < 1000; i++) { | |
Foo foo = new Foo(); | |
Thread t1 = new Thread(() -> { | |
foo.x = 1; | |
foo.y = 1; | |
}); | |
Thread t2 = new Thread(()-> { | |
while (foo.y != 1) { | |
if (foo.x == 1) counter.incrementAndGet(); | |
} | |
}); | |
t1.start(); | |
t2.start(); | |
t1.join(); | |
t2.join(); | |
} | |
// выводится рандомное число | |
System.out.println(counter.get()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment