3 Replies Latest reply: Apr 12, 2007 3:50 PM by DrClap RSS

    Synchronized run

    807606
      Suppose we have:
      public class Synco1 extends Thread {
      
           static int i=0;
           Object o;
           int j=0;
           public Synco1(Object o){
                this.o=o;
           }
           public syncronized void run(){
                while (j<5){
                     //synchronized (o){
                          System.out.print(Thread.currentThread()+"i before increase "+ i);
                          try{
                          Thread.sleep(1000);
                          }catch(InterruptedException e) {System.out.print("Exception");};
                          j++;
                          i++;
                          System.out.println(" ");
                          System.out.print(Thread.currentThread()+"i afther increase"+ i);
                          System.out.println(" ");
                     //}
                     
                }
           }
      }
       
      
      
      public class Synco1Tester {
      
           /**
            * @param args
            */
           public static void StartThread(Thread t){
                t.start();
           }     
           public static void main(String[] args) {
                // TODO Auto-generated method stub
                Integer p=new Integer(1);
                Synco1 t1=new Synco1(p);
                t1.setName("Thread1");
                Synco1 t2=new Synco1(p);
                t2.setName("Thread2");
                StartThread(t1);
                StartThread(t2);
      
           
           
           }
      
      }
      I know the correct way to synchronize is like // syncronize (o) , but why public syncronize run (); doesn't synchronize the method run? (excuse the mess word)
        • 1. Re: Synchronized run
          807606
          By synchronizing the run method, you prevent this method to be called concurrently on a given instance of Synco1 (synchronized instance methods use this as the lock).
          In other words:
          synchronized void method() {
              // code
          }
          is equivalent to
          void method() {
              synchronized(this) {
                  // code
              }
          }
          • 2. Re: Synchronized run
            807606
            excuse me, TimTheEnchantor, you say:

            you prevent this method to be called concurrently on a given instance of Synco1

            I don' understand.

            Why can i use the syncronized on the refence this and not on the method run?
            • 3. Re: Synchronized run
              DrClap
              Because you always use an object as a synchronization lock, not a method. That's how Java works. Read the tutorial:

              http://java.sun.com/docs/books/tutorial/essential/concurrency/