forked from greasymolue/SF-Int-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCounter.java
More file actions
36 lines (30 loc) · 1.01 KB
/
Counter.java
File metadata and controls
36 lines (30 loc) · 1.01 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
package runnables;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
public class Counter {
public static long count = 0;
// public static AtomicLong count = new AtomicLong();
public static void main(String[] args) throws InterruptedException {
Runnable r = () -> {
for (int i = 0; i < 1_000_000_000L; i++) {
synchronized (Counter.class) {
count++;
}
// count.incrementAndGet();
}
};
System.out.println("count is " + count);
long start = System.nanoTime();
Thread t = new Thread(r);
t.start();
Thread t2 = new Thread(r);
t2.start();
// "happens-before" says "if you look then you will see"..
// join creates a happens-before relationship from the end of the thread (that dies)
// to the continuation of the calling thread
t.join();
t2.join();
long time = System.nanoTime() - start;
System.out.println("count is " + count + ". Time was " + (time / 1_000_000_000.0));
}
}