File tree Expand file tree Collapse file tree
src/EConcurrency/Secure/Synchronized Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments