synchronized是公平锁还是非公平锁
做再多猜想也不如直接写个案例,验证一下,直接上代码:
public class TestSynchronized { public volatile boolean flag;//通知什么时候发起新的请求 //拿住锁5秒钟,以便对后面请求锁进行阻塞 public synchronized void blockWhile(){ try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } //调用该方法时,会被阻塞住 public synchronized void blockMethod(){ if (!this.flag){this.flag = true;} System.out.println("block Method : " + System.currentTimeMillis()); } //执行新的方法 public synchronized void newMethod(){ System.out.println("new Method : " + System.currentTimeMillis()); } public static void main(String[] args) throws InterruptedException { TestSynchronized testSynchronized = new TestSynchronized(); Thread a = new Thread(testSynchronized::blockWhile); a.start(); Thread.sleep(10);//确保a线程获得锁 Thread b = new Thread(() -> { for (int i = 0; i