Skip to content

Commit 1b51812

Browse files
synchronized计数器
1 parent 1b71ae0 commit 1b51812

2 files changed

Lines changed: 51 additions & 0 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package EConcurrency.Secure.Synchronized;
2+
3+
/**
4+
* @author CodeCoderCoding
5+
*/
6+
public class Counter {
7+
8+
private int count;
9+
10+
public synchronized void incr(){
11+
count ++;
12+
}
13+
14+
public synchronized int getCount() {
15+
return count;
16+
}
17+
18+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package EConcurrency.Secure.Synchronized;
2+
3+
/**
4+
* @author CodeCoderCoding
5+
*/
6+
public class UseCounter extends Thread{
7+
Counter counter;
8+
9+
public UseCounter(Counter counter) {
10+
this.counter = counter;
11+
}
12+
13+
@Override
14+
public void run() {
15+
for(int i= 0; i<1000; i++) {
16+
counter.incr();
17+
}
18+
}
19+
20+
public static void main(String[] args) throws InterruptedException {
21+
int num = 1000;
22+
Counter counter = new Counter();
23+
Thread[] threads = new Thread[num];
24+
for (int i = 0; i < num; i++) {
25+
threads[i] = new UseCounter(counter);
26+
threads[i].start();
27+
}
28+
for (int i = 0; i < num; i++) {
29+
threads[i].join();
30+
}
31+
System.out.println(counter.getCount());
32+
}
33+
}

0 commit comments

Comments
 (0)