Java
자바 thread

class Buffer
{
    private int data; //케익
    private boolean empty = true; //케익이 비었음표시
    public synchronized int get() //케익을 사는 메소드
    {
        while(empty)
        {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        empty=true;
        notifyAll(); //생산자들 꺠우기
        return data;
    }
    public synchronized void put(int data) //케익 생산
    {
        while(!empty)
        {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            empty = false;
            this.data=data;
            notifyAll(); // 소비자를 꺠우기
    
        }
    }
}
class producer extends Thread
{
    private Buffer buffer;
    public producer(Buffer buffer)
    {
        this.buffer=buffer;
    }
    public void run()
    {

        for(int i=1; i<=10; i++)
        {
            buffer.put(i); //생산
            System.out.println("생산자"+i+"번째 케익을 생성하였습니다");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class cusumer extends Thread
{
    private Buffer buffer;
    public cusumer(Buffer buffer)
    {
        this.buffer=buffer;
    }
    public void run()
    {
        int data = 0;
        for(int i=1; i<=10; i++)
        {
            data=buffer.get(); //소비
            System.out.println("구매자"+data+"번째 케익을 소비하였습니다");
    
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                
            }
        }
    }
}
public class Test1 {

    public static void main(String[] args) {
        Buffer obj = new Buffer();
        producer p1 = new producer(obj);
        cusumer c1 = new cusumer(obj);
        
        p1.start();
        c1.start();
    }

}
 

소비자가 나오지 않습니다.

댓글 1