執行緒通訊舉例1 管程法

changbaishannefu發表於2020-09-26

//生產者生產物品,消費者消費物品

package Syco;

public class Contactbetwen {

    public static void main(String[] args) {
        contain contain = new contain();
        new consumer(contain).start();
        new producer(contain).start();

    }
}


class food{
int id;

    public food(int id) {
        this.id = id;
    }
}

class consumer extends Thread{

    contain contain;
    public consumer(contain contain){

        this.contain=contain;

    }

    @Override
    public void run() {
        for (int i = 1; i <1000 ; i++) {
            synchronized(contain){
                if(contain.count==0){
                    try {

                        contain.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
                contain.count--;
                food f=contain.f[contain.count];
                System.out.println("消費了第"+f.id+"個");
                contain.notifyAll();

            }


        }
    }
}


class producer extends Thread{

    contain contain;
    public  producer(contain contain){

        this.contain=contain;
    }

    @Override
    public void run() {
        for (int i = 1; i < 1000; i++) {
            synchronized (contain){
                if(contain.count==10){

                    try {
                        contain.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }


                contain.f[contain.count]= new food(i);
                contain.count++;
                System.out.println("生產了第"+i+"件");
                contain.notifyAll();

            }

        }
    }
}

class contain {

food[] f=new food[10];
int count=0;




}

相關文章