ThreadPropTest.java Download this source file



// ThreadPropTest - Are the properties of a class private to
// each Thread or are they shared?  They are shared!
// Written 2/2001 by Wayne Pollock, Tampa Florida USA.

class User
{
   private String name;  // This is per object, not per thread.

   User ( String name )
   {  this.name = name;  }

   public String getName ()
   {  return name;  }

   public void setName ( String name )
   {  this.name = name;  }
}

class ThreadPropTest implements Runnable
{
   private User user;

   public ThreadPropTest ( User user )
   {  this.user = user;  }

   public static void main ( String [] args )
   {
      // Create a single object that all threads share:
      User u = new User( "Stooge" );

      // Create some Threads:
      new Thread( new ThreadPropTest(u), "Moe" ).start();
      new Thread( new ThreadPropTest(u), "Larry" ).start();
      new Thread( new ThreadPropTest(u), "Curly" ).start();
   }

   public void run ()
   {
      Thread me = Thread.currentThread();
      user.setName( me.getName() );
      for ( int i = 0; i < 3; ++i )
      {
         System.out.println( me.getName() + " : user = " + user.getName() );
         try { Thread.sleep( (int) ( Math.random() * 100 ) ); }
         catch ( InterruptedException ignored ) {}
      }
   }
}




  ThreadLocalTest.java Download this source file



// ThreadLocalTest - How to have the properties of a class private to
// each Thread.
// Written 2/2001 by Wayne Pollock, Tampa Florida USA.

class User
{
   private ThreadLocal name = new ThreadLocal();

   User ( String name )
   {  this.name.set( name );  }

   public String getName ()
   {  return (String) name.get();  }

   public void setName ( String name )
   {  this.name.set( name );  }
}

class ThreadLocalTest implements Runnable
{
   private User user;

   public ThreadLocalTest ( User user )
   {  this.user = user;  }

   public static void main ( String [] args )
   {
      // Create a single object that all threads share:
      User u = new User( "Stooge" );

      // Create some Threads:
      new Thread( new ThreadLocalTest(u), "Moe  " ).start();
      new Thread( new ThreadLocalTest(u), "Larry" ).start();
      new Thread( new ThreadLocalTest(u), "Curly" ).start();
   }

   public void run ()
   {
      Thread me = Thread.currentThread();
      user.setName( me.getName() );
      for ( int i = 0; i < 3; ++i )
      {
         System.out.println( me.getName() + " : user = " + user.getName() );
         try { Thread.sleep( (int) ( Math.random() * 100 ) ); }
         catch ( InterruptedException ignored ) {}
      }
   }
}


Send comments and mail to the WebMaster.