Skip to content
Advertisement

Multiple thread failed to execute the nonsynchronized code in java

If Thread1 get the lock and start executing the synchronized block, During the same time,Thread2 is free to execute the non-synchronized part of the code which is IntStream.range(0, 5).forEach(x -> System.out.println("thread Unsafe Zone,"+name)).

Unexpectedly,below is what actually happening while i run code.

Explaintation-

Suppose,thread1(or thread2) get the lock and execute the synchronized block and then thread2( or thread1) get the lock released by thread1(or thread2) and execute the synchronized block.After both thread complete the execution of synchronized block, then both thread parellelly start executing the non-synchronized part. I run the code multiple time hoping to get the desired output but fail to avail.

Demo class

JavaScript

Thread1 class

JavaScript

Thread2 class

JavaScript

Display class

JavaScript

Output:

JavaScript

Advertisement

Answer

If Thread1 get the lock and start executing the synchronized block, During the same time,Thread2 is free to execute the non-synchronized part of the code: not exactly.

In execution order the non-synchronized block follows the synchronized block. Therefore you will never see any thread executing the non-synchronized block before the synchronized block.

The best what you can hope for is something like

JavaScript

where the thread 2 enters the synchronized block while thread 1 is running in the non-synchronized block.

You can increase the chance for such an outcome by changing your Display.getname() method by calling Thread.yield(); after the synchronized block and by doing more System.out.println() calls:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement