Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Why does the Java program CriticalSectionFailedSynchronized.java fail to print m

ID: 3558783 • Letter: W

Question

Why does the Java program CriticalSectionFailedSynchronized.java fail to print messages correctly?

code:

package criticalSection;


public class CriticalSectionFailedSynchronize
{
   static String message = "Now Is The Time For All Good Men ";
   static int numThreads = 200;

   public static void main(String args[])
   {
       for (int idx = 0; idx < numThreads; idx++) {
           Thread t = new Thread(new StreamPrinter());
           t.start();
       }
   }

   static class StreamPrinter implements Runnable
   {
       static Integer lock = 1;

       @Override
       public void run()
       {
           while (true) {
               printMessage();
           }
       }

       private synchronized void printMessage()
       {
           byte chars[] = message.getBytes();
           for (int idx = 0; idx < chars.length; idx++) {
               byte achar = chars[idx];
               System.out.write((char) achar);
               Thread.yield();
           }
       }
   }
}

Explanation / Answer

Because of this ifinite loop

while (true) {
               printMessage();
           }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote