public class Sync { public static void main(String[] args) throws InterruptedException { Executors.newCachedThreadPool().submit(new Static(Loker.class)); Thread.sleep(1000); Loker.call(); }}class Loker{ public static synchronized void call(){ System.out.println("call in"); }}class Static implements Callable{ private Object locker; public Static(Object loker){ this.locker=loker; } @Override public Object call() throws Exception { synchronized (locker){ Thread.sleep(4000); System.out.println("sleep end"); } return null; }}
可以看到结果每次都要sleep end才能call in
也就是说静态方法加锁是通过Class对象来加锁的
这样也证明了一个类只有一个Class对象,(因为synchronized是通过==来比较的)