📜  门| GATE-CS-2016(Set 2)|问题6(1)

📅  最后修改于: 2023-12-03 15:42:18.361000             🧑  作者: Mango

GATE-CS-2016(Set 2) - 问题6

这是GATE-CS-2016(Set 2)中的第6个问题。题目要求我们对给定的Java代码进行分析并回答几个问题。

代码分析

首先我们来看一下代码片段:

public final class Example {
   private static char[] buffer = new char[256];

   public static void main(String args[]) {
      buffer[0] = 'a';
      buffer[1] = 'b';
      PrintString t1 = new PrintString();
      PrintString t2 = new PrintString();
      t1.start();
      t2.start();
   }

   private static void print(String str) {
      int len = str.length();
      synchronized (buffer) {
         for (int i = 0; i < len; i++) {
            buffer[i] = str.charAt(i);
         }
         System.out.println(buffer);
      }
   }

   private static class PrintString extends Thread {
      public void run() {
         print("xyz");
      }
   }
}

我们注意到该代码创建了两个线程对象,分别启动了这两个线程,同时这两个线程都调用了PrintString类中的run()方法,在该方法中调用了print()方法打印了字符串"xyz",打印时采用了同步锁。

问题回答
1. 假设两个PrintString线程同时运行,并且CPU时间片轮流分配给两个线程,输出的结果是什么?

由于两个线程分别执行了print()方法,而print()方法又使用了同步锁,因此在任意时刻只有一个线程可以访问缓冲区,并进行输出操作。

因此,输出结果的第一部分将是线程1将"xyz"写入缓冲区,第二部分是线程2将"xyz"写入缓冲区,而最后的输出结果是"xy"或"yz"或"zx"。

2. 如果PrintString线程的run()方法改为不同步的输出会发生什么?

如果remove the synchronized block, there would be a data race condition where the threads are concurrently modifying and accessing the shared buffer. This means that the output string could be garbled and not contain the expected "xyz" string. It's also possible that one thread completely overwrites the buffer before the other has a chance to print its own string, causing one or both threads to hang. Therefore, it is important to ensure a thread-safe access to shared data.