- During the interview, I encountered a question about synchronize and static synchronization, such as the title
In fact, my understanding is completely deviated, so after I came back, I studied it carefully and wrote a simpleDemo for your reference.
Summary: Adding synchronized to the front of the method is similar to the synchronized{xxxxxxx} code block, both are synchronized(this){xxxx} (Does it feel terrible?)
To lock the object, remember that it locks the entire object. If static is synchronized, the class is locked, so the answer is clear at a glance.
If you pursue performance, it is recommended that you use synchronized with caution
Answer:
can not
can not
can not
can not
can
The demo is as follows
package cn.com.flaginfo; import java.util.Date; import java.util.concurrent.TimeUnit; public class A { private static boolean isTrue; private static Object sss = new Object(); public static synchronized void staticWrite(boolean b) throws InterruptedException{ System.out.println("staticWrite·" + new Date()); TimeUnit.SECONDS.sleep(2); isTrue = b; } public static synchronized boolean staticRead() throws InterruptedException{ System.out.println("staticRead·"+ new Date()); TimeUnit.SECONDS.sleep(2); return isTrue; } public synchronized void write(boolean b) throws InterruptedException{ System.out.println("write·"+ new Date()); TimeUnit.SECONDS.sleep(2); isTrue = b; } public void write1(boolean b) throws InterruptedException{ synchronized(sss){ System.out.println("write·"+ new Date()); TimeUnit.SECONDS.sleep(2); isTrue = b; } } public synchronized boolean read() throws InterruptedException{ System.out.println("read·"+ new Date()); TimeUnit.SECONDS.sleep(2); return isTrue; } public static void main(String[] args) throws Exception{ final A a = new A(); new Thread(new Runnable(){ @Override public void run() { try { System.out.println("调用staticWrite(true)"); a.write(true); // A.staticWrite(true); } catch (InterruptedException e) { e.printStackTrace (); } } }).start(); TimeUnit.MILLISECONDS.sleep(200); new Thread(new Runnable(){ @Override public void run() { try { System.out.println("调用staticRead()"); // A.staticRead(); a.read(); } catch (InterruptedException e) { e.printStackTrace (); } } }).start(); } }