title: Java-Synchronized String result in interference
body: <p>I am using a simple program where 2 threads are defined to simply count down from 10. I have a ThreadColor class simply to be able to color the 2 threads in different colors.
      package com.sherif;</p>
  
  <pre><code>public class Main {
  
  public static void main(String[] args) {
  
      Countdown countdown = new Countdown();
  
      CountdownThread t1 = new CountdownThread(countdown);
      t1.setName("Thread 1");
      t1.start();
  
      CountdownThread t2 = new CountdownThread(countdown);
      t2.setName("Thread 2");
      t2.start();
  
      }
  }
  
  class Countdown {
  private int i;
  String color;
  
  public void doCountdown() {
      switch (Thread.currentThread().getName()) {
          case "Thread 1":
              color = ThreadColor.ANSI_BLUE;
              break;
  
          case "Thread 2":
              color = ThreadColor.ANSI_RED;
              break;
  
          default:
              color = ThreadColor.ANSI_CYAN;
  
      }
  
      synchronized (color) {
          for (i = 10; i &gt; 0; i--) {
              System.out.println(color + Thread.currentThread().getName() + "   i= " + i);
          }
        }
     }
  }
  
  class CountdownThread extends Thread {
  
  private Countdown countdown;
  
  public CountdownThread(Countdown countdown) {
      this.countdown = countdown;
  }
  
  @Override
  public void run() {
  
      this.countdown.doCountdown();
      }
  }
  </code></pre>
  
  <p>I am synchronizing the for loop that counts down to avoid interference using the color object. Although I am defining the color as an instance variable that both threads share it still creates interference.
  However, when I use a different string it works just fine.
  I know that I can use synchronized on (this), but I would like to understand what exactly is going on. </p>