Repository navigation
Expand file tree
/
Copy pathMainConcurrency.java
More file actions
68 lines (56 loc) · 1.84 KB
/
Copy pathMainConcurrency.java
File metadata and controls
68 lines (56 loc) · 1.84 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.javaops.run;
import java.util.ArrayList;
import java.util.List;
/**
* @author Vasichkin Pavel
*/
public class MainConcurrency {
public static final int THREAD_NUMBER = 10000;
private static int counter;
private static final Object LOCK = new Object();
public static void main(String[] args) throws InterruptedException {
System.out.println(Thread.currentThread().getName());
Thread thread0 = new Thread() {
@Override
public void run() {
System.out.println(getName() + ", " + getState());
}
};
thread0.start();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + Thread.currentThread().getState());
}
}).start();
new Thread(() -> System.out.println(Thread.currentThread().getName())).start();
System.out.println(thread0.getState());
final MainConcurrency mainConcurrency = new MainConcurrency();
List<Thread> threads = new ArrayList<>(THREAD_NUMBER);
for (int i = 0; i < THREAD_NUMBER; i++) {
Thread thread = new Thread(() -> {
for (int j = 0; j < 100; j++) {
mainConcurrency.increment();
}
});
thread.start();
threads.add(thread);
}
threads.forEach(thread -> {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println(counter);
}
private void increment() {
// synchronized (this) {
// synchronized (MainConcurrency.class)
double a = Math.sin(13.);
synchronized (LOCK) {
counter++;
}
}
}