JAVA 생산자 소비자(스레드 동기화) 코드 학습 예

1. 문제 설명
생산자 소비자 문제는 전형적인 라인 동기화 문제다.생산자가 상품을 생산하여 용기에 넣으면 용기는 일정한 용량(순서대로 놓을 수 있고 먼저 놓고 나중에 가져갈 수 있다)이 있고 소비자가 상품을 소비한다. 용기가 가득 차면 생산자가 기다리고 용기가 비어 있을 때 소비자가 기다린다.생산자가 상품을 용기에 넣은 후 소비자에게 통지한다.소비자가 상품을 가져간 후 생산자에게 통지하다.
2. 솔루션
용기 자원에 자물쇠를 채워야 자물쇠를 얻은 후에야 상호 배척 자원에 대해 조작할 수 있다.

public class ProducerConsumerTest {

    public static void main(String []args){
        Container con = new Container();
        Producer p = new Producer(con);
        Consumer c = new Consumer(con);
        new Thread(p).start();
        new Thread(c).start();
    }

}


class Goods{
    int id;
    public Goods(int id){
        this.id=id;
    }

    public String toString(){
        return " "+this.id;
    }
}

class Container{// ,
    private int index = 0;
    Goods[] goods = new Goods[6];

    public synchronized void push(Goods good){
        while(index==goods.length){// ,
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        goods[index]=good;
        index++;
        notifyAll();//
    }

    public synchronized Goods pop(){
        while(index==0){//
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        index--;
        notifyAll();//
        return goods[index];
    }
}

class Producer implements Runnable{

    Container con = new Container();
    public Producer(Container con){
        this.con=con;
    }

    public void run(){
        for(int i=0; i<20; i++){
            Goods good = new Goods(i);
            con.push(good);
            System.out.println(" :"+good);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}

class Consumer implements Runnable{

    Container con = new Container();
    public Consumer(Container con){
        this.con=con;
    }

    public void run(){
        for(int i=0; i<20; i++){
            Goods good=con.pop();
            System.out.println(" :"+good);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

   
}

좋은 웹페이지 즐겨찾기