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]

  • 相关阅读:
    基于python检测端口是否在使用
    一行CMD命令kill(杀)掉你的进程
    Python 线程与进程
    Linux07 文件查找(locate、find )及特殊权限(SUID、SGID、Sticky)
    Linux06 vim文本编辑器的使用
    Linux04 shell编程1
    Linux03 重定向,管道,文件查找(grep)
    Linux02(目录、文件、用户、用户组管理)
    Linux01
    pytest装饰器
  • 原文地址:https://www.cnblogs.com/hailiang2013/p/2846432.html
Copyright © 2011-2022 走看看