[Java并发]Synchronized

public class AtomicTest01 {
    public static int i = 0;
    public static void main(String[] args) {
        Runnable task = new Runnable(){
            @Override
            public void run() {
                synchronized (this){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.print(i++ + " ");
                }
            }
        };
        for (int j = 0; j < 10; j++) {
            Thread thread = new Thread(task);
            thread.start();
        }
    }
}

synchronized锁住的到底是什么

如果synchronized加在普通方法上,锁住的其实是this,也就是当前实例对象

class Test{
    public synchronized void test() {
    }
}
//等价于
class Test{
    public void test() {
        synchronized(this) {
        }
    }
}

如果synchronized加在静态方法上,锁住的其实是该类的class字节码文件

class Test{
    public synchronized static void test() {
    }
}

//等价于
class Test{
    public static void test() {
        synchronized(Test.class) {
        }
    }
}

synchronized关键字加在代码块上,锁住的对象要自己指定,可以是实例对象,可以是class对象,也可以是自定义对象

posted @ 2024-07-09 19:08  Duancf  阅读(1)  评论(0编辑  收藏  举报