1 Reply Latest reply: Jul 10, 2012 11:05 AM by gimbal2 RSS

    Problem with Java Multithreading Synchronization

    948531
      I'm not able to synchronize a block of my code using synchronized keyword for the method.
      Ideally if a method is synchronized, only 1 thread can access across multiple threads. But output is executing in that manner.

      Code attached below

      class SyncClass
      {
           synchronized void synMthd(String s)
           {
                System.out.println("[ "+s);
                try
                {
                     Thread.sleep(3000);
                }
                catch(Exception e)
                {
                     System.out.println(e);
                }
                System.out.println(" ]");
           }
      }
      class Test implements Runnable
      {
           public static void main(String ar[])
           {
                Test tt = new Test();
                Thread t1 = new Thread(tt,"T1");
                Thread t2 = new Thread(tt,"T2");
                t1.start();
                t2.start();
           }

           public void run()
           {
                SyncClass syn = new SyncClass();
                Thread th = Thread.currentThread();
      //          synchronized(syn)
      //          {
                     syn.synMthd(th.getName());
      //          }
           }     
      }     

      when I'm executing this code, both the threads accessing synMthd method simultaneously.

      Please help me on this.
        • 1. Re: Problem with Java Multithreading Synchronization
          gimbal2
          That's because each thread is invoking the method on a unique personal instance of SyncClass. There is nothing shared between the two threads; thread T1 will put a lock on its own instance of SyncClass and Thread T2 will put a lock on its own instance of SyncClass; they won't ever see each other's locks.

          Try modifying your code such that the threads call synMthd on the exact same instance of SyncClass because that's when things are likely to go boom when concurrently running code.

          And btw: use \
           tags to post code to make it readable.