JAVA Basic 강의자료] wait(), notify()의 사용 예제
JAVA Basic 강의자료] wait(), notify()의 사용 예제
실무개발자를위한 실무교육 전문교육센터학원
www.oraclejava.co.kr에 오시면 보다 다양한 강좌를 보실 수 있습니다.
wait(), notify()의 사용 예제(1)
<소스코드>
import java.util.*;
class SyncStack{
private Vector buffer = new Vector();
public synchronized char pop(){
char c;
while(buffer.size()==0){
try{
System.out.println("stack대기:");
this.wait();
}catch(Exception e){}
}
Character cr = ((Character)buffer.remove(buffer.size()-1));
c = cr.charValue();
System.out.println("stack삭제:" + c);
return c;
}
public synchronized void push(char c){
this.notify();
Character charObj = new Character(c);
buffer.addElement(charObj);
System.out.println("stack삽입:" + c);
}
}
===============
class PopRunnable extends Thread{
public void run(){
SyncTest.ss.pop();
}
}
class PushRunnable extends Thread{
private char c;
public PushRunnable(char c){
this.c =c ;
}
public void run(){
SyncTest.ss.push(c);
}
}
wait(), notify()의 사용 예제(2)
<소스코드>
public class SyncTest {
public static SyncStack ss =new SyncStack();
public static void main(String[] args){
//SyncStack에 5데이터삽입
new PushRunnable('J').start();
new PushRunnable('A').start();
new PushRunnable(‘V').start();
new PushRunnable(‘A').start();
new PushRunnable('O').start();
new PopRunnable().start();//O
new PopRunnable().start();//A
new PopRunnable().start();//V
new PopRunnable().start();//A
new PopRunnable().start();//J
new PopRunnable().start();//대기상태
try{
Thread.sleep(5000);
}catch(Exception e){}
System.out.println("===== passed 5 seconds======");
new PushRunnable('K').start();
}
}
'자바 > Java공부하기' 카테고리의 다른 글
JAVA Basic 강의자료] Reflection의 의미 (0) | 2016.09.19 |
---|---|
JAVA Basic 강의자료] getClass() (0) | 2016.09.19 |
JAVA Basic 강의자료] wait(), notify(), notifyAll() (0) | 2016.09.19 |
JAVA Basic 강의자료] Clone()의 사용 방법 (0) | 2016.09.19 |
JAVA Basic 강의자료] clone() (0) | 2016.09.12 |