forked from Java2ArkTS/Java2ArkTS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCounterTest.java
More file actions
61 lines (48 loc) · 1.31 KB
/
Copy pathCounterTest.java
File metadata and controls
61 lines (48 loc) · 1.31 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
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
System.out.println(" incremented count to " + count);
}
public synchronized void decrement() {
count--;
System.out.println(" decremented count to " + count);
}
public synchronized int getCount() {
return count;
}
}
class IncrementTask implements Runnable {
private Counter counter;
public IncrementTask(Counter counter) {
this.counter = counter;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
counter.increment();
}
}
}
class DecrementTask implements Runnable {
private Counter counter;
public DecrementTask(Counter counter) {
this.counter = counter;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
counter.decrement();
}
}
}
public class CounterTest {
public static void main(String[] args) {
Counter counter = new Counter();
Thread incrementThread = new Thread(new IncrementTask(counter));
Thread decrementThread = new Thread(new DecrementTask(counter));
incrementThread.start();
decrementThread.start();
System.out.println("Final count: " + counter.getCount());
}
}