/* 2개의 쓰레드가 코드와 데이터를 공유하는 상황
* t2 쓰레드는 데이터의 값이 50이상이 될때까지 기다렸다가 실행될 수 있도록 조건을 설정함
* synchronized를 적용하여 데이터의 일관성 확보하려고 했다
* synchronized블럭 안에서 sleep()을 사용하는 경우 Dead Lock가능성이 있다.
* 이 소스를 실행하면 잠시 실행되던 중에 Dead Lock현상을 보임
* 대책: synchronized 블럭 내에서 sleep()을 사용하여 대기하는 것을 피하고
* wait(), notify()를 사용해야 한다.
*/
class Code3 implements Runnable{
int i = 0;
public void run(){
String name = null;
while(i<100){
synchronized(this) {
name = Thread.currentThread().getName();
if(name.equals("t2")) {
while(i<50) {
try{
Thread.sleep(100);
}catch(InterruptedException e){}
}
}
i++;
System.out.println(name+"시작:"+i);
try{
Thread.sleep(30);
}catch(InterruptedException e){}
System.out.println(name+"끝:"+i);
}
}
}
public static void main(String[] args) {
Code3 code = new Code3();
Thread t1 = new Thread(code);
Thread t2 = new Thread(code);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
}