zoukankan      html  css  js  c++  java
  • Productor and Customer problem

    [code=java]

    class Person
    {
     
        private String name="llj";
        private String content="";
        private boolean flag=false;
        public synchronized void set(String name,String content)
        {
         //flag 标志用来是否可以设置,否则等待
         //如果是假,表示等待不能去设置
         if(flag)
         {   
          try {
        wait();
       } catch (Exception e) {
        // TODO: handle exception
       }
         }
         this.name=name;
         try {
       Thread.sleep(100);
      } catch (Exception e) {
       // TODO: handle exception
      }
         this.content=content;
         //设置完成后更改标志flag为true
         flag=true;
         notifyAll();
        }
        public synchronized String get()
        {
         if(flag==false)
         {
          try {
        wait();
       } catch (Exception e) {
        // TODO: handle exception
       }
         }
         flag=false;
         notifyAll();
         String str=this.name+"-->"+this.content;
         return str;
        }
    }

    class Pro implements Runnable
    {
     private Person per=null;
     public Pro(Person per)
     {
      this.per=per;
     }
     public void run() {
      // TODO Auto-generated method stub
      for(int i=0;i<100;i++)
      {
       if(i%2==0)
       {
        per.set("MLDN", "网站");
        
       }
       else {
        per.set("LLJ","作者");
       }
      }
     }}
    class Cus implements Runnable
    {
     private Person per=null;
     public Cus(Person per)
     {
      this.per=per;
     }
     public void run() {
      // TODO Auto-generated method stub
      for (int i = 0; i < 100; i++) {
       
       System.out.println(per.get());
      }
      
     }
     
    }
    public class ThreadDemo6 {
     public static void main(String args[])
     {
      Person per=new Person();
      Pro p=new Pro(per);
      Cus c=new Cus(per);
      new Thread(p).start();
      new Thread(c).start();
     }
    }

    [/code]

  • 相关阅读:
    菜鸟解决“子页面关闭刷新父页面局部”问题的历程
    ORACLE基本SQL语句-查询篇
    ORACLE基本SQL语句-添加更新数据函数篇
    ORACLE基本SQL语句-用户及建表篇
    关于JVM
    调用微信支付接口总结
    Oracle入门
    C#使用 SharpAVI进行 屏幕录制
    window 下编译cef 内核 加入mp3/mp4 支持
    python 模块 optparse
  • 原文地址:https://www.cnblogs.com/hailiang2013/p/2846432.html
Copyright © 2011-2022 走看看