码迷,mamicode.com
首页 > 编程语言 > 详细

线程---消费生产

时间:2018-08-18 16:25:08      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:.com   class   rgs   err   data   int   nts   ret   ima   

/*
        线程
    生产和消费
*/

class SynStack 
{
    private char[] data = new char[6];
    private int cnt = 0; //表示数组有效元素的个数
    
    public synchronized void push(char ch)
    {
        while (cnt == data.length)
        {
            try
            {
                this.wait();
            }
            catch (Exception e)
            {
            }
        }
        this.notify(); 
        
        data[cnt] = ch;
        ++cnt;
        System.out.printf("生产线程正在生产第%d个产品,该产品是: %c\n", cnt, ch);
    }
    
    public synchronized char pop()
    {
        char ch;
        
        while (cnt == 0)
        {
            try
            {
                this.wait();
            }
            catch (Exception e)
            {
            }
        }
        this.notify();
        ch = data[cnt-1];
        
        System.out.printf("消费线程正在消费第%d个产品,该产品是: %c\n", cnt, ch);
        
        --cnt;
        return ch;        
    }    
}

class Producer implements Runnable
{
    private SynStack ss = null;
    
    public Producer(SynStack ss)
    {
        this.ss = ss;
    }
    
    public void run() // throws Exception
    {
        //push(‘a‘);  //error
        char ch;
        
        for (int i=0; i<20; ++i)
        {
//            try{
//            Thread.sleep(100);
//            }
//            catch (Exception e){            
//            }
                
            ch = (char)(‘a‘+i);
            ss.push(ch);
        }
    }
}

class Consumer implements Runnable
{
    private SynStack ss = null;
    
    public Consumer(SynStack ss)
    {
        this.ss = ss;
    }
    
    public void run()
    {
        for (int i=0; i<20; ++i)
        {
            try{
            Thread.sleep(100);
            }
            catch (Exception e){            
            }
            
            //System.out.printf("%c\n", ss.pop());
            ss.pop();
        }
    }
}


public class TestPC
{
    public static void main(String[] args)
    {
        SynStack ss = new SynStack();
        Producer p = new Producer(ss);
        Consumer c = new Consumer(ss);
        Thread t1 = new Thread(p);
        t1.start();
                
        Thread t2 = new Thread(c);
        t2.start();
    }
}

技术分享图片

 

线程---消费生产

标签:.com   class   rgs   err   data   int   nts   ret   ima   

原文地址:https://www.cnblogs.com/6530265oule/p/9497451.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!