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  
  • 相关阅读:
    [转] 浅谈 C++ 中的 new/delete 和 new[]/delete[]
    [转] dpkg-deb命令
    [转] 将DOS格式文本文件转换成UNIX格式
    STM32与FreeRTOS实现低功耗
    设置Beyond Compare 为 Git 默认的比较工具
    [转]Linux进程间通信——使用消息队列
    还你一个自由、干净的网络环境
    Linux下的Hello world
    Cortex-M3中C与汇编的交互
    数据结构25:矩阵转置算法(三元组顺序表)
  • 原文地址:https://www.cnblogs.com/cynchanpin/p/6923761.html
Copyright © 2011-2022 走看看