Java多线程实现生产者消费者模型

2019-09-20 11:35:08阅读 143评论 0

定义一个功能栈

package test;
class Stack
{
    private char[] data = new char[6];
    private int cnt = 0;
    public synchronized boolean push(char ch)
    {
        boolean status = false;
        if(cnt < 6)
        {
            status = true;
            data[cnt] = ch;
            cnt++;
            System.out.printf("已生成第%d个商品\n", cnt);
        }
        return status;
    }
    public synchronized boolean pop()
    {
        boolean status = false;
        if(cnt > 0)
        {
            status = true;
            System.out.printf("已消费第%d个商品\n", cnt);
            cnt--;
        }
        return status;
    }
}
/*定义一个功能栈*/

定义生产者

class Producer implements Runnable
{
    public Stack s = null;
    public Producer(Stack s)
    {
        this.s = s;
    }
    public void run()
    {
        while(true)
        {
            try
            {
                Thread.currentThread().sleep(500);
            }
            catch(Exception e)
            {}
            boolean status = this.s.push('a');
            if(status == false)
            {
                try
                {
                    this.wait();
                }
                catch(Exception e)
                {}
            }
        }
    }
}
/*定义生产者*/

定义一个消费者

class Cusummer implements Runnable
{
    public Stack s = null;
    public Cusummer(Stack s)
    {
        this.s = s;
    }
    public void run()
    {
        while(true)
        {
            try
            {
                Thread.currentThread().sleep(1000);
            }
            catch(Exception e)
            {}
            boolean status = this.s.pop();
            if(status == false)
            {
                try
                {
                    this.notify();
                }
                catch(Exception e)
                {}
            }
        }
    }
}
/*定义一个消费者*/

主线程

public class PCtest
{
    public static void main(String[] args)
    {
        Stack s = new Stack();
        //声明并初始化一个功能栈  
        Producer p = new Producer(s);
        Thread tt1 = new Thread(p);
        tt1.start();
        //开启生产者线程  
        Cusummer c = new Cusummer(s);
        Thread tt2 = new Thread(c);
        tt2.start();
        //开启消费者线程  
    }
}

还没有评论,来说两句吧