forked from Java2ArkTS/Java2ArkTS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultiThreadAccumulator.java
More file actions
38 lines (31 loc) · 937 Bytes
/
Copy pathMultiThreadAccumulator.java
File metadata and controls
38 lines (31 loc) · 937 Bytes
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
class Accumulator {
private int sum;
public synchronized void addToSum(int value) {
sum += value;
System.out.println(" added " + value + ". Current sum: " + sum);
}
public synchronized int getSum() {
return sum;
}
}
class AdderTask implements Runnable {
private Accumulator accumulator;
private int valueToAdd;
public AdderTask(Accumulator accumulator, int valueToAdd) {
this.accumulator = accumulator;
this.valueToAdd = valueToAdd;
}
@Override
public void run() {
accumulator.addToSum(valueToAdd);
}
}
public class MultiThreadAccumulator {
public static void main(String[] args) {
Accumulator accumulator = new Accumulator();
Thread thread1 = new Thread(new AdderTask(accumulator, 5));
Thread thread2 = new Thread(new AdderTask(accumulator, 10));
thread1.start();
thread2.start();
}
}