* Thread state control method
sleep()
스레드를 CPU 점유상태(running) 에서 대기 상태로 돌아가고, 다른 스레드에게 CPU권한을 넘겨줌.
public static void sleep(long miliseconds ) throws InterruptedException
사용 예 )
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
sleep method를 사용하는 동안에는 InterruptedException 이 발생할 수 있기 때문에 try & catch 를 이용한다.
그 외에 yield(), notify(), wait() 등이 있다.
사용 예 )
/* 스택 */
class MyStack {
int index = 0;
char[] data = new char[6];
public void push(char c) {
sychronized(this) {
this.notify();
data[index] = c;
index++;
}
}
public char pop() {
synchronized(this) {
try {
while( data.length == 0 )
this.wait();
} catch(InterruptException) {}
index--;
return data[index];
}
}
}
* Synchronization 키워드
멀티 스레딩 환경에서 동일한 자료를 동시에 접근하여 데이터의 충돌이 생기는 것을 방지하기 위함.
=> synchronized 키워드를 사용하여 공유자원에 대한 독점권을 부여해 데이터 충돌을 방지한다.
1. 메소드 동기화
public synchronized void setData( String data ) { }
2. 일부 코드 동기화
public void setData( String data ) {
synchronized(this) {
// 동작 구현
}
}
'Programming > JAVA' 카테고리의 다른 글
JAVA AWT (0) | 2010.02.24 |
---|---|
JAVA java.io 패키지 (0) | 2010.02.24 |
JAVA Thread (0) | 2010.02.23 |
JAVA 예외처리 (0) | 2010.02.23 |
JAVA Collection API (0) | 2010.02.23 |