利用面向对象的思想实现主从线程下多次循环的切换(因为他们要同步,所以他们是有关联的,所以把它们放在一个类里)

 1 import java.util.concurrent.atomic.AtomicInteger;

 2 

 3 public class TraditionalThreadCommunication {

 4 

 5     /**

 6      * @param args

 7      */

 8     public static void main(String[] args) {

 9         

10         final Business business = new Business();

11         new Thread(

12                 new Runnable() {

13                     

14                     @Override

15                     public void run() {

16                     

17                         for(int i=1;i<=50;i++){

18                             business.sub(i);

19                         }

20                         

21                     }

22                 }

23         ).start();

24         

25         for(int i=1;i<=50;i++){

26             business.main(i);

27         }

28         

29     }

30 

31 }

32   class Business {

33       private boolean bShouldSub = true;

34       public synchronized void sub(int i){

35           while(!bShouldSub){

36               try {

37                 this.wait();

38             } catch (InterruptedException e) {

39                 // TODO Auto-generated catch block

40                 e.printStackTrace();

41             }

42           }

43             for(int j=1;j<=10;j++){

44                 System.out.println("sub thread sequence of " + j + ",loop of " + i);

45             }

46           bShouldSub = false;

47           this.notify();

48       }

49       

50       public synchronized void main(int i){

51               while(bShouldSub){

52                   try {

53                     this.wait();

54                 } catch (InterruptedException e) {

55                     // TODO Auto-generated catch block

56                     e.printStackTrace();

57                 }

58               }

59             for(int j=1;j<=100;j++){

60                 System.out.println("main thread sequence of " + j + ",loop of " + i);

61             }

62             bShouldSub = true;

63             this.notify();

64       }

65   }

 

你可能感兴趣的:(面向对象)