追求性能的话, 建议大家慎用synchronized
?
答案:?
不能
不能
不能
不能
能
?
demo 如下
?
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(); } }
?