Data Share 04
/* 2개의 쓰레드가 코드와 데이터를 공유하는 상황
* t2 쓰레드는 데이터의 값이 50이상이 될때까지 기다렸다가 실행될 수 있도록 조건을 설정함
* synchronized를 적용하여 데이터의 일관성 확보하려고 했다
* synchronized블럭 안에서 wait()을 사용하여 Dead Lock을 예방한다.
* 이 소스를 실행하면 t2 쓰레드가 Wait Pool에서 대기하다가
* t1 쓰레드가 통보할 경우, 풀에서 나와서 활동을 다시 시작한다.
* 데이터의 일관성, 병행처리, Dead Lock 등의 문제가 모두 해제되었다.
*
*/
class Code5 implements Runnable{
int i = 0;
public void run(){
String name = null;
while(i<100){
synchronized(this) {
name = Thread.currentThread().getName();
if(name.equals("t2")) {
if(i<50) {
try{
wait();
}catch(InterruptedException e){}
}
}
i++;
if(i>=50) notifyAll();
System.out.println(name+"시작:"+i);
try{
Thread.sleep(30);
}catch(InterruptedException e){}
System.out.println(name+"끝:"+i);
}
try{
Thread.sleep(30);
}catch(InterruptedException e){}
}
}
public static void main(String[] args) {
Code5 code = new Code5();
Thread t1 = new Thread(code);
Thread t2 = new Thread(code);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
}