-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathThreadWay3.java
40 lines (32 loc) · 857 Bytes
/
ThreadWay3.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
40
public class ThreadWay3 {
public static class Counter {
int count;
public synchronized void increment() {
count++;
}
}
public static void main(String[] args) {
Counter counter = new Counter();
Runnable obj1 = () -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
};
Runnable obj2 = () -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
};
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(counter.count);
}
}