No matter how many guesses you make, it's better to write a case directly , Check it out , Code directly :
public class TestSynchronized { public volatile boolean flag;// Inform when to initiate a new request
// Hold the lock 5 second , In order to block the subsequent request lock public synchronized void blockWhile(){ try {
Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } }
// When the method is called , It will be blocked public synchronized void blockMethod(){ if
(!this.flag){this.flag = true;} System.out.println("block Method : " +
System.currentTimeMillis()); } // Implement new methods 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);// ensure a Thread gets lock
Thread b = new Thread(() -> { for (int i = 0; i < 50;i++){
testSynchronized.blockMethod(); } }); b.start();//b Thread blocking 50 Method requests
System.out.println("finish block Method : " + System.currentTimeMillis());
Thread c = new Thread(() -> { int i = 0; while (true){ if
(testSynchronized.flag){ for ( ; i < 50;i++){ testSynchronized.newMethod(); } }
} }); c.start();//c Thread in b After execution of thread blocking method , To execute the new calling method , Simulate the competition effect of new request method and blocking queue request method } }
The results are as follows , The execution result has strong randomness , Increase the number of execution or increase the number of method execution can have a high probability of the following results :
finish block Method : 1591683424652 block Method : 1591683429643 block Method
: 1591683429643 block Method : 1591683429643 block Method : 1591683429643 new
Method : 1591683429643 new Method : 1591683429643 block Method : 1591683429643
block Method : 1591683429643 block Method : 1591683429643 ......
explain ,synchronized Right and wrong fair lock , There is no waste of thread wake-up time , Execute the newly called method , Increase throughput , The disadvantage is that it can cause starvation .
Technology