-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVolatileMain.java
More file actions
45 lines (37 loc) · 1.29 KB
/
VolatileMain.java
File metadata and controls
45 lines (37 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.thread;
class VolatileData{
private volatile int counter =0;
public int getCounter() {
return counter;
}
public void increaseCounter() {
++counter;
}
}
class VolatileThread extends Thread{
private final VolatileData volatileData;
public VolatileThread(VolatileData volatileData) {
this.volatileData=volatileData;
}
@Override
public void run() {
int oldValue = volatileData.getCounter();
System.out.println("[Thread " + Thread.currentThread().getId() + "]: Old value = " + oldValue);
volatileData.increaseCounter();
int newValue = volatileData.getCounter();
System.out.println("[Thread " + Thread.currentThread().getId() + "]: New value = " + newValue);
}
}
public class VolatileMain {
private final static int noOfThreads = 2;
public static void main(String[] args) throws InterruptedException {
VolatileData volatileData = new VolatileData(); //object of VolatileData class
Thread[] threads = new Thread[2]; //creating Thread array
for(int i = 0; i < noOfThreads; ++i)
threads[i] = new VolatileThread(volatileData);
for(int i = 0; i < noOfThreads; ++i)
threads[i].start(); //starts all reader threads
for(int i = 0; i < noOfThreads; ++i)
threads[i].join(); //wait for all threads
}
}