Skip to content

Commit 771ec33

Browse files
author
Rajeev Kumar Singh
committed
Volatile Keyword Example
1 parent 18ac416 commit 771ec33

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
public class MemoryConsistencyErrorExample {
2+
private static boolean sayHello = false;
3+
4+
public static void main(String[] args) throws InterruptedException {
5+
6+
Thread thread = new Thread(() -> {
7+
while(!sayHello) {
8+
9+
}
10+
11+
System.out.println("Hello World!");
12+
13+
while(sayHello) {
14+
15+
}
16+
17+
System.out.println("Good Bye!");
18+
});
19+
20+
thread.start();
21+
22+
Thread.sleep(1000);
23+
System.out.println("Say Hello..");
24+
sayHello = true;
25+
26+
Thread.sleep(1000);
27+
System.out.println("Say Bye..");
28+
sayHello = false;
29+
}
30+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
public class VolatileKeywordExample {
2+
private static volatile boolean sayHello = false;
3+
4+
public static void main(String[] args) throws InterruptedException {
5+
6+
Thread thread = new Thread(() -> {
7+
while(!sayHello) {
8+
9+
}
10+
11+
System.out.println("Hello World!");
12+
13+
while(sayHello) {
14+
15+
}
16+
17+
System.out.println("Good Bye!");
18+
});
19+
20+
thread.start();
21+
22+
Thread.sleep(1000);
23+
System.out.println("Say Hello..");
24+
sayHello = true;
25+
26+
Thread.sleep(1000);
27+
System.out.println("Say Bye..");
28+
sayHello = false;
29+
}
30+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy