1- package com .algorithm ;
2-
3- import java .util .concurrent .atomic .AtomicInteger ;
4-
5- public class TestAsynTreadXunlei {
6- public static void main (String argv []) {
7-
8- AtomicInteger synObj = new AtomicInteger (0 );
9-
10- TestPrint a = new TestPrint (synObj , "A" , 0 );
11- TestPrint b = new TestPrint (synObj , "B" , 1 );
12- TestPrint c = new TestPrint (synObj , "C" , 2 );
13-
14- a .start ();
15- b .start ();
16- c .start ();
17- }
18- }
19-
20- class TestPrint extends Thread {
21-
22- private AtomicInteger synObj ;
23- private String name ;
24- private int flag ;
25-
26- private int count = 0 ;
27-
28- public TestPrint (AtomicInteger synObj , String name , int flag ) {
29- this .synObj = synObj ;
30- this .name = name ;
31- this .flag = flag ;
32- }
33-
34- @ Override
35- public void run () {
36- while (true ) {
37- synchronized (synObj ) {
38- if (synObj .get () % 3 == flag ) {
39- synObj .set (synObj .get () + 1 );
40- System .out .println (name +synObj .get ());
41- count ++;
42- synObj .notifyAll ();
43- if (count == 10 ) {
44- break ;
45- }
46- } else {
47- try {
48- synObj .wait ();
49- } catch (InterruptedException e ) {
50- // TODO Auto-generated catch block
51- e .printStackTrace ();
52- }
53- }
54- }
55- }
56- }
1+ package com .algorithm ;
2+
3+ import java .util .concurrent .atomic .AtomicInteger ;
4+
5+ public class TestAsynTreadXunlei {
6+ public static void main (String argv []) {
7+
8+ AtomicInteger synObj = new AtomicInteger (0 );
9+
10+ TestPrint a = new TestPrint (synObj , "A" , 0 );
11+ TestPrint b = new TestPrint (synObj , "B" , 1 );
12+ TestPrint c = new TestPrint (synObj , "C" , 2 );
13+
14+ a .start ();
15+ b .start ();
16+ c .start ();
17+ }
18+ }
19+
20+ class TestPrint extends Thread {
21+
22+ private AtomicInteger synObj ;
23+ private String name ;
24+ private int flag ;
25+
26+ private int count = 0 ;
27+
28+ public TestPrint (AtomicInteger synObj , String name , int flag ) {
29+ this .synObj = synObj ;
30+ this .name = name ;
31+ this .flag = flag ;
32+ }
33+
34+ @ Override
35+ public void run () {
36+ while (true ) {
37+ synchronized (synObj ) {
38+ if (synObj .get () % 3 == flag ) {
39+ synObj .set (synObj .get () + 1 );
40+ System .out .println (name +synObj .get ());
41+ count ++;
42+ synObj .notifyAll ();
43+ if (count == 10 ) {
44+ break ;
45+ }
46+ } else {
47+ try {
48+ synObj .wait ();
49+ } catch (InterruptedException e ) {
50+ // TODO Auto-generated catch block
51+ e .printStackTrace ();
52+ }
53+ }
54+ }
55+ }
56+ }
5757}
0 commit comments