비정상적인 방법의 자물쇠는 실례적인 대상 자체(this)이고, 정적 방법의 자물쇠는 클래스 대상 자체(.class)이다.

2994 단어 자물쇠
public class LockTest {

    public static void main(String[] args) {
        MyThread mt = new MyThread();

        Thread t1 = new Thread(mt);
        Thread t2 = new Thread(mt);
        t1.start();
        try {
            Thread.sleep(10);
        } catch (Exception e) {}

        mt.flag = false;
        t2.start();
    }
}

class MyThread implements Runnable{

    private  int num = 100;
    boolean flag = true;
    @Override
    public void run() {
        if(flag){
            while(true){
                synchronized(this){    //    
                    if(num > 0){
                        try {
                            Thread.sleep(10);
                            System.out.println(Thread.currentThread().getName()+"__run__"+num--);
                        } catch (Exception e) {}
                    }
                }   
            }
        } else{
            while(true){
                this.show();
            }
        }
    }

    public synchronized void show(){     //    
        if(num > 0){
            try {
                Thread.sleep(10);
                System.out.println(Thread.currentThread().getName()+"__show__"+num--);
            } catch (Exception e) {}

        }
    }

}

좋은 웹페이지 즐겨찾기