Listing 6: File Independent5.java: Reveals interleaved output

class MyThread extends Thread
{
   private int delay;
   private int count;
   public MyThread(String msg, int delay, int count)
   {
      super(msg); // Optional thread name
      this.delay = delay;
      this.count = count;
   }
   public void run()
   {
      for (int i = 0; i < count; ++i)
      {
         try
         {
            Thread.sleep(delay);
            display();
         }
         catch (InterruptedException x)
         {
            // Won't happen in this example
         }
      }
   }
   void display()
   {
      String s = getName();
      for (int i = 0; i < s.length(); ++i)
         System.out.print(s.charAt(i));
      System.out.println();
   }
}

class Independent5
{
   public static void main(String[] args)
   {
      Thread t1 = new MyThread("DessertTopping", 100, 8);
      Thread t2 = new MyThread("FloorWax", 200, 4);
      t1.start();
      t2.start();
   }
}

/* Output:
DessertTopping
FloorWax
DessertTopping
DessertTopping
FloorDessertTopping
Wax
DessertTopping
FloorWax
DessertTopping
DessertTopping
FloDessertTopping
orWax
*/
— End of Listing —