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();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.