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 injava
也就是说静态方法加锁是经过Class对象来加锁的ide
这样也证实了一个类只有一个Class对象,(由于synchronized是经过==来比较的)this