zoukankan      html  css  js  c++  java
  • Java经典线程同步问题------生产者与消费者

    先上代码

    1. class Test  
    2. {  
    3.     public static void main(String []args)  
    4.     {  
    5.         Queue q=new Queue();  
    6.         Producer p=new Producer(q);  
    7.         Consumer c=new Consumer(q);  
    8.         p.start();  
    9.         c.start();  
    10.     }  
    11. }  
    12.   
    13. class Producer extends Thread  
    14. {  
    15.     Queue q;  
    16.     Producer(Queue q)  
    17.     {  
    18.         this.q=q;  
    19.     }  
    20.     public void run()  
    21.     {  
    22.         for(int i=0;i<10;i++)  
    23.         {     
    24.             q.put(i);  
    25.             System.out.println("Producer put"+i);  
    26.         }  
    27.     }  
    28. }  
    29. class Consumer extends Thread  
    30. {  
    31.     Queue q;  
    32.     Consumer(Queue q)  
    33.     {  
    34.         this.q=q;  
    35.     }  
    36.     public void run()  
    37.     {  
    38.         while(true)  
    39.         {  
    40.             System.out.println("Consumer get"+q.get());  
    41.         }  
    42.     }     
    43. }  
    44.   
    45. class Queue  
    46. {  
    47.     int value;  
    48.     boolean bFull=false;  
    49.     public synchronized void put(int i)  
    50.     {  
    51.           
    52.         if(!bFull)  
    53.         {  
    54.         value=i;  
    55.         bFull=true;  
    56.         notify();  
    57.         }  
    58.     try{  
    59.     wait();  
    60.     }  
    61.     catch(Exception e)  
    62.     {}  
    63.     }  
    64.     public synchronized int get()  
    65.     {  
    66.     if(!bFull)  
    67.     {  
    68.         try  
    69.         {  
    70.             wait();  
    71.         }  
    72.         catch(Exception e)  
    73.         {  
    74.           
    75.         }  
    76.     }  
    77.     bFull=false;  
    78.     notify();  
    79.     return value;  
    80.     }  
    81. }  

    执行结果

    1. Producer put0  
    2. Consumer get0  
    3. Consumer get1  
    4. Producer put1  
    5. Consumer get2  
    6. Producer put2  
    7. Consumer get3  
    8. Producer put3  
    9. Consumer get4  
    10. Producer put4  
    11. Consumer get5  
    12. Producer put5  
    13. Consumer get6  
    14. Producer put6  
    15. Consumer get7  
    16. Producer put7  
    17. Consumer get8  
    18. Producer put8  
    19. Consumer get9  
    20. Producer put9  
  • 相关阅读:
    忘记线上MySQL密码:
    Auth认证
    swoole定时
    hashMap,hashTable,concurrentHashmap的区别
    JSP中URL路径获取问题
    #Spring代理的简单例子#
    #动态代理#
    #类加载机制#
    #算法#二分查找和插入(start end交叉的地方)
    #tomcat#生成的jsp转换问题
  • 原文地址:https://www.cnblogs.com/cynchanpin/p/6923761.html
Copyright © 2011-2022 走看看