• java多线程生产者消费者


    //Java Thread  producer customer
    class ThreadTest
    {
         public static void main(String[] args)
         {
             Q q=new Q();
             
             Producer p=new Producer(q);
             Customer c=new Customer(q);
             Thread t0=new Thread(p);
             Thread t1=new Thread(c);
             t0.start();
             t1.start();
             
             for(int i=0;i<50;i++)
             {
                 if(i==25)
                 {
                    p.stop();
                    c.stop();
                 }
                 
                 System.out.println(Thread.currentThread().getName());
             }
         }
    }
    
    class Q
    {
         String name="empty";
         String gender="empty";
         boolean isEmpty=true;
         
         public synchronized void Put(String name,String gender)
         {
            if (!isEmpty) {
                try {wait();} catch (Exception ex) {}
            }
            this.name = name;
            try {Thread.sleep(1);} catch (Exception ex) {}
            this.gender = gender;
            isEmpty = false;
            notify();
         }
    
         public synchronized void Get()
         {
             if(isEmpty)
             {
                 try{wait();}catch(Exception ex){}
             }
             System.out.println("name:"+this.name+"__gender:"+this.gender);
             isEmpty=true;
             notify();
         }
    }
    
    class Producer implements Runnable
    {
        Q q;
        boolean isStop=false;
        public void stop()
        {
            this.isStop=true;
        }
        public Producer(Q q)
        {
            this.q=q;
        }
    
        public void run() {
            int i = 0;
            while (!isStop) {
                if (i == 0) {
                    q.Put("Tim", "male");
    
                } else {
                    q.Put("Lian", "female");
                }
                i = (i + 1) % 2;
            }
        }
    }
    
    class Customer implements Runnable
    {
        Q q;
        boolean isStop=false;
        public void stop()
        {
            this.isStop=true;
        }
        public Customer(Q q)
        {
            this.q=q;
        }
        public void run()
        {
            while(!isStop)
            {
                q.Get();
            }
        }
    }
    View Code

     

  • 相关阅读:
    html5--6-10 CSS选择器7--伪类选择器
    html5--6-9 CSS选择器6--伪类选择器
    html5--6-8 CSS选择器5
    避开美国全球监控阴影下的问题手机,寻求新伙伴
    DMA过程分析
    混淆
    Missile:双状态DP
    Java抓取网页数据(原网页+Javascript返回数据)
    Binders 与 Window Tokens(窗体令牌)
    编程之美2013 初赛一 A
  • 原文地址:https://www.cnblogs.com/tim-li/p/3395637.html
Copyright © 2020-2023  润新知