package CHAPTER12;

//공유 객체 (테이블 역할): 셰프와 손님이 요리를 주고받는 공간
class Table {
	private String food; // 준비된 음식
	private boolean ready = false; // 음식 준비 상태

	// 요리 제공 (셰프 역할)
	public synchronized void put(String item) {
		while (ready) { // 이전 음식이 아직 소비되지 않았다면 대기
			try {
				wait();
			} catch (InterruptedException e) {
			}
		}

		this.food = item;
		this.ready = true;
		System.out.println("셰프가 준비한 요리: " + item);

		notifyAll(); // 대기 중인 손님 스레드 깨움
	}

	// 음식 소비 (손님 역할)
	public synchronized void take() {
		while (!ready) { // 음식이 아직 준비되지 않았다면 대기
			try {
				wait();
			} catch (InterruptedException e) {
			}
		}

		System.out.println("손님이 먹은 요리: " + food);
		this.ready = false;

		notify(); // 대기 중인 셰프 스레드 깨움
	}
}

public class C12_05_NotifyTest { // 생산자-소비자 패턴 (notify/wait 사용 예제)
	public static void main(String[] args) {
		Table table = new Table();

		// 셰프 스레드 (생산자 역할)
		Thread chef = new Thread(() -> {
			String[] menu = { "파스타", "스테이크", "피자", "샐러드" };
			for (String dish : menu) {
				table.put(dish); // 요리 제공
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
				}
			}
		});

		// 손님 스레드 (소비자 역할)
		Thread customer = new Thread(() -> {
			for (int i = 0; i < 4; i++) {
				table.take(); // 음식 소비
				try {
					Thread.sleep(1500);
				} catch (InterruptedException e) {
				}
			}
		});

		// 스레드 시작
		chef.start();
		customer.start();
	}
}
