4.传统线程同步通信技术

 1 /**
 2  * 传统线程同步通信技术
 3  * 
 4  * *******************************************
 5  * 经验:
 6  *       要用到共同数据(包括共同锁)或共同算法的若干个方法应该
 7  * 归在用一个类身上,这种设计正好体现了高内聚和程序的健壮性。
 8  * 
 9  * *******************************************
10  *  
11  * @author LiTaiQing
12  */
13 public class TraditionalThreadCommunication {
14 
15     /**************************************************
16      * 调试小技巧
17      * 如果由于Console的输出太多而造成面板显示的数据不完整
18      * 可设置运行前参数设置
19      * 右键->Run As->Run Configuractions->Common->File
20      * 选择保存的路径即可
21      * 
22      **************************************************
23      */
24     
25     
26     /**
27      * 面试题 
28      * ·子线程循环10次,接着主线程循环100,接着又回到子线程循环10次, 
29      * ·接着再回到主线程又循环100,如此循环50次,请写出程序
30      */
31     public static void main(String[] args){
32         
33         final Business business = new Business();
34         new Thread(new Runnable(){
35             @Override
36             public void run() {
37                 for(int i = 1; i <= 50; i++){
38                     business.sub(i);
39                 }
40             }
41         }).start();
42         for(int i = 1; i <= 50; i++){
43             business.main(i);
44         }
45     }
46 
47 }
48 
49 class Business{
50     private boolean bShouldSub = true;
51     public synchronized void sub(int i){
52         /**
53          * 此处将if改为while,增强代码健壮性。
54          * 防止伪唤醒!
55          */
56         while(!bShouldSub){
57             try {
58                 this.wait();
59             } catch (InterruptedException e) {
60                 e.printStackTrace();
61             }
62         }
63         for(int j = 1; j <= 10; j++){
64             System.out.println("sub thread sequece of " + j + ",loop of " +i);
65         }
66         bShouldSub = false;
67         this.notify();
68     }
69     public synchronized void main(int i){
70         while(bShouldSub){
71             try {
72                 this.wait();
73             } catch (InterruptedException e) {
74                 e.printStackTrace();
75             }
76         }
77         for(int j = 1; j <= 100; j++){
78             System.out.println("main thread sequece of " + j + ",loop of " +i);
79         }
80         bShouldSub = true;
81         this.notify();
82     }
83 }
原文地址:https://www.cnblogs.com/litaiqing/p/4635188.html