1 Reply Latest reply on Jul 10, 2012 4:05 PM by gimbal2

    Problem with Java Multithreading Synchronization

      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);
                catch(Exception 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");

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

      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
          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.