[211125] 교육 25일차

oxllz·2022년 2월 7일
0

교육

목록 보기
19/41

스레드

wait(), notify()

class ShampooAI extends Thread {
	private Table tbl = null;
	public ShampooAI( Table t ) {
		this.tbl = t;
	}
	public void run() {
		for( int i = 0 ; i < 300 ; i++ ) {
			String d = "dish " + i;
			tbl.on( d );
		}
	}
}
//
class WashAI extends Thread {
	private Table tbl = null;
	public WashAI( Table t ) {
		this.tbl = t;
	}
	public void run() {
		for( int i = 0 ; i < 300 ; i++ ) {
			String d = tbl.off();
		}
	}
}
//
class Table {
	private List<String> dishes = null;
	public Table() {
		dishes = new LinkedList<String>();
	}
    //
	public synchronized void on( String dish ) {  
		while( dishes.size() == 5 ) {
			try {
				wait();	//	이 함수 호출하는 쓰레드야 너 멈춰
			}
			catch( InterruptedException e ){}
		}
		System.out.println( dish + " : on the table" );
		dishes.add( dish ); 
		notify();
    //
	public synchronized String off() {
		while( dishes.size() == 0 ) {
			try {
				wait();	//	이 함수 호출하는 쓰레드야 너 멈춰 ( 여기서는 워시가 된다 )
			}
			catch( InterruptedException e ){}
		}
		String d = dishes.remove( dishes.size() - 1 );
		System.out.println( d + " : off the table" );
		notify();	//	자신이 멈춘 쓰레드를 다시 일하도록 한다.
		return d;
	}
}
//
public class Test219 {
	public static void main( String[] args ) {
		Table table = new Table();
		Thread s = new ShampooAI( table );
		Thread w = new WashAI( table );
		s.start();
		w.start();
	}
}
실행결과>>
dish 0 : on the table
dish 0 : off the table
dish 1 : on the table
dish 1 : off the table
dish 2 : on the table
dish 2 : off the table
dish 3 : on the table
dish 3 : off the table
dish 4 : on the table
dish 4 : off the table
dish 5 : on the table
dish 5 : off the table

설거지를 예로 들자면 그릇에 거품을 묻히는 사람과 씻는 사람은 동시에 일을 하고 있다. 이때 서로의 속도를 맞춰서 일하도록 설정한다. wait() 거품을 칠하는 사람은 그릇이 5장이 쌓이면 멈추고 씻는 사람은 그릇이 0장이 되면 씻을 것이 없기 때문에 기다려야 한다. notify() 그 후 그릇이 5장 이하가 되거나 씻을 그릇이 생기면 다시 동작한다.

0개의 댓글