IT/자바

쓰레드 데드락

Beautifulkim 2018. 5. 18. 11:44
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62

package mymain;
 
//이건 내부 클래스 아님
//Runnable : 대기
//서로 못깨우는 상태 waite pool에 갖힌 상태 : 데드락 상태(어설프게 작성할 경우 데드락걸림)
class MyRunnable3 implements Runnable 
{
    @Override
    public void run() {
        // TODO 자동 생성된 메소드 스텁
        
        String name = Thread.currentThread().getName();
        
        while (true) {
            
            /*
                 synchronized 안에서만 사용가능(동기화 블록 내에서만 사용해야함)
                 notify();, wait();
                 
                 [ 순서 ] 
                 1_꺠우고나서(wait pool:잠들어있는 방) 
                 2_대기방에 들어감(Runnable) 
                 3_그리고 CPU가 대기방에서 실행함
             */
            synchronized (this
            {
                //진입과 동시에 잠들어 있는 쓰레드를 깨운다.
                //notify();//깨움//wait pool에 대기방에 들어감
                //notifyAll(); : 여러명이 들어가 있을때 한꺼번에 깨우는 메소드
                
                
                
                System.out.printf("-- [%s] 먼저---\n", name);
                try {
                    //자신의 코드를 처리한 후에 스스로 잠든다(대기상태로)
                    wait();
                    
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    // TODO 자동 생성된 catch 블록
                    e.printStackTrace();
                }
            }
        }
    }
}
 
 
public class MyMain_데드락 {
 
    public static void main(String[] args) {
        // TODO 자동 생성된 메소드 스텁
        MyRunnable3 runnable =  new MyRunnable3();
        Thread t1 = new Thread(runnable,"▶1_형님");
        Thread t2 = new Thread(runnable,"◀2_아우");
        
        t1.start();
        t2.start();
    }
 
}
 
cs