-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCasMainV3.java
More file actions
51 lines (42 loc) · 1.52 KB
/
Copy pathCasMainV3.java
File metadata and controls
51 lines (42 loc) · 1.52 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
46
47
48
49
50
51
package thread.cas;
import util.MyLogger;
import util.ThreadUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class CasMainV3 {
private static final int THREAD_COUNT = 2;
public static void main(String[] args) throws InterruptedException {
AtomicInteger atomicInteger = new AtomicInteger(0);
System.out.println("start value = " + atomicInteger.get());
Runnable runnable = new Runnable() {
@Override
public void run() {
increamentAndGet(atomicInteger);
}
};
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < THREAD_COUNT; i++) {
Thread thread = new Thread(runnable);
threads.add(thread);
thread.start();
}
for (Thread thread : threads) {
thread.join();
}
int result = atomicInteger.get();
System.out.println(atomicInteger.getClass().getSimpleName() + " resultValue : " + result);
}
public static int increamentAndGet(AtomicInteger atomicInteger){
int getValue;
boolean result;
do{
getValue = atomicInteger.get();
ThreadUtils.sleep(100); // 스레드 동시 실행을 위한 대기
MyLogger.log("getValue : " + getValue);
result = atomicInteger.compareAndSet(getValue, getValue+1);
MyLogger.log("result : " + result);
}while(!result);
return getValue + 1;
}
}