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