- 동기화와 wait(), notify()
-> 데이터의 동기화와 관련해 쓰레드를 미세하게 제어하는 메서드
=> wait() : 쓰레드를 Not Runnable 영역으로 보냄
=> notify(), notifyAll(), : wait() 에 의해 Not Runnable영역으로 보내진 쓰레드를 Runnable영역으로 보냄
=> synchronized 선언된 곳에서 사용
=================================================================================================================
import java.util.Vector;
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) {
// TODO: handle exception
}
}
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{
@Override
public void run() {
// TODO Auto-generated method stub
SyncTest.ss.pop();
}
}
class PushRunnable extends Thread{
private char c;
public PushRunnable(char c){
this.c = c;
}
@Override
public void run() {
// TODO Auto-generated method stub
SyncTest.ss.push(c);
}
}
public class SyncTest {
public static SyncStack ss = new SyncStack();
public static void main(String[] args) {
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) {
// TODO: handle exception
}
System.out.println("======= passed 5 seconds======");
new PushRunnable('K').start();
}
}
'프로그래밍 정리 > 자바' 카테고리의 다른 글
Reflection(리플렉션) (0) | 2013.07.11 |
---|---|
getClass() (0) | 2013.07.11 |
clone() (0) | 2013.07.11 |
finalize() (0) | 2013.07.11 |
hashCode() (0) | 2013.07.11 |