java面试之synchronized 和 static synchronized 博客分类: java面试总结 java面试synchronizedstatic synchronized
程序员文章站
2024-02-05 16:24:22
...
- 面试的时候遇到了题目关于synchronize 和static synchronized的问题 , 如题
其实我的理解 完全偏差 , 因此回来后认真的研究了下, 写了个simpleDemo 供大家参考,
总结: synchronized 加到方法前面 和 synchronized{ xxxxxxx} 代码块类似 , 都是synchronized(this){xxxx}(有木有感觉很可怕?)
将该对象 加锁, 记住, 是锁住整个对象, 若static的synchronized则锁的是这个class, 所以答案也就一目了然了。
追求性能的话, 建议大家慎用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(); } }