zoukankan      html  css  js  c++  java
  • 线程同步生产者消费者问题

     1 public class ProducerConsumer{
     2     public static void main(String[] args){
     3         WtStack st = new WtStack();
     4         Producer a = new Producer(st);
     5         Consumer b = new Consumer(st);
     6         new Thread(a).start();
     7         new Thread(b).start();
     8     }
     9 }
    10 
    11 class WoTou {
    12     int id;
    13     WoTou(int id){
    14         this.id=id;
    15     }
    16     public String toString(){
    17         return "WoTou: "+id;
    18     }
    19 }
    20 
    21 class WtStack {
    22     int index=0;
    23     WoTou[] wtarr = new WoTou[10];
    24     
    25     public synchronized void push(WoTou wt){
    26         while(index==wtarr.length){
    27             try{
    28                 this.wait();
    29             }catch(InterruptedException e){
    30                 e.printStackTrace();
    31             }
    32         }
    33         this.notify();
    34         wtarr[index]= wt;
    35         index++;    
    36     }
    37     
    38     public synchronized WoTou pop(){
    39         while(index==0){
    40             try{
    41                 this.wait();
    42             }catch(InterruptedException e){
    43                 e.printStackTrace();
    44             }
    45         }
    46         this.notify();
    47         index--;
    48         return wtarr[index];
    49     }
    50 }
    51 
    52 class Producer implements Runnable {
    53     WtStack st = null;
    54     Producer(WtStack a){
    55         this.st = a;
    56     }
    57     public void run(){
    58         for(int i=0;i<20;i++){
    59             WoTou wt = new WoTou(i);
    60             st.push(wt);
    61             System.out.println("生产了:"+wt);
    62         }
    63         try{
    64             Thread.sleep(1000);
    65         }catch(InterruptedException e){
    66             e.printStackTrace();
    67         }
    68     }
    69 }
    70 
    71 class Consumer implements Runnable {
    72     WtStack st = null;
    73     Consumer(WtStack a){
    74         this.st = a; 
    75     }
    76     public void run(){
    77         for(int i=0;i<20;i++){
    78             System.out.println(st.pop());
    79         }
    80         try{
    81             Thread.sleep(1000);
    82         }catch(InterruptedException e){
    83             e.printStackTrace();
    84         }
    85     }
    86 }
  • 相关阅读:
    增量+全量备份SVN服务器
    日常小命令集锦
    filebeat输出到kafka
    在Logstash的配置文件中对日志事件进行区分
    NFS服务器简易安装
    记录一次MySQL数据库CPU负载异常高的问题
    使用Spring的jdbcTemplate进一步简化JDBC操作
    Stream 和 byte[] 之间的转换
    C# 文件转byte数组,byte数组再转换文件
    groupbox里面添加Form
  • 原文地址:https://www.cnblogs.com/humanchan/p/3020851.html
Copyright © 2011-2022 走看看