天天看點

多生産者多消費者執行個體

package multithread;

class Resource
{
    private String name;
    private int count = ;
    private boolean flag = false;
    public synchronized void set(String name)//  
    {
        while(flag)
            try{this.wait();}catch(InterruptedException e){}//   t1    t0

        this.name = name + count;//烤鴨1  烤鴨2  烤鴨3
        count++;//2 3 4
        System.out.println(Thread.currentThread().getName()+"...生産者..."+this.name);//生産烤鴨1 生産烤鴨2 生産烤鴨3
        flag = true;
        notifyAll();
    }

    public synchronized void out()//  t3
    {
        while(!flag)
            try{this.wait();}catch(InterruptedException e){}    //t2  t3
        System.out.println(Thread.currentThread().getName()+"...消費者........"+this.name);//消費烤鴨1
        flag = false;
        notifyAll();
    }
}

class Producer implements Runnable
{
    private Resource r;
    Producer(Resource r)
    {
        this.r = r;
    }
    public void run()
    {
        while(true)
        {
            r.set("烤鴨");
        }
    }
}

class Consumer implements Runnable
{
    private Resource r;
    Consumer(Resource r)
    {
        this.r = r;
    }
    public void run()
    {
        while(true)
        {
            r.out();
        }
    }
}



class  Threaddemo
{
    public static void main(String[] args) 
    {
        Resource r = new Resource();
        Producer pro = new Producer(r);
        Consumer con = new Consumer(r);

        Thread t0 = new Thread(pro);
        Thread t1 = new Thread(pro);
        Thread t2 = new Thread(con);
        Thread t3 = new Thread(con);
        t0.start();
        t1.start();
        t2.start();
        t3.start();

    }
}