-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConcurrency.java
39 lines (31 loc) · 1.11 KB
/
Concurrency.java
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
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Java의 built-in 아토믹 인크레멘터를 사용 -> thread safe
* 일반 primitive 사용 -> thread unsafe (lock이 없음)
*
* 각 thread는 join 하지 않으면 프로그램 조기 종료됨
*/
public class Concurrency {
private static class Counter extends Thread {
public static int items = 0;
public static AtomicInteger aItems = new AtomicInteger(0);
public void run() {
for (int i = 0; i < 1_000_000; i++) {
items++;
aItems.incrementAndGet();
}
}
}
public static void main(String args[]) throws InterruptedException {
List<Counter> list = new ArrayList<>();
for (int i = 0; i < 2; i++) {
list.add(new Counter());
}
for (Counter c : list) c.start();
for (Counter c : list) c.join();
System.out.println("Total sum int (not correct): " + Counter.items);
System.out.println("Total sum AtomicInteger (correct): " + Counter.aItems);
}
}