非静的メソッドのロックはインスタンスオブジェクト自体(this)、静的メソッドのロックはクラスオブジェクト自体(.class)

2988 ワード

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) {}

        }
    }

}