0
public class B extends Thread {

    @Override
    public void run() {
        print();
    }

    public synchronized void print(){
    int i;
        for (i=0;i<1000;i++){
        System.out.println(Thread.currentThread().getName() );
        }
    }

}

public class A {
    public static void main(String[] args) {
        B b1=new B();
        B b2=new B();

        b1.start();
        b2.start();
    }
}

How to lock the print method acessing two objects of the class B ? What I am wanting is here I ve synchronized the method there is no use of it ! so I want the thread 1 to run the print method 1st and then thread 2 . How can I change the code?

Sathiyakugan
  • 674
  • 7
  • 20

2 Answers2

1

You can use thread.join() as shown in the below code with inline comments:

class B code:

public class B extends Thread {

        @Override
        public void run() {
            print();
        }

        //Remove synchronized
        public void print(){
            int i;
            for (i=0;i<1000;i++){
                System.out.println(Thread.currentThread().getName());
            }
        }
    }

class A code:

public class A {

    public static void main(String[] args) throws Exception {
            B b1=new B();
            B b2=new B();

            b1.start();//start first thread

            b1.join();//Use join, to let first thread complete its run()

            b2.start();//run second thread
      }
 }

Also, as a side note, I recommend you to use class B implements Runnable than extending Thread.

Vasu
  • 21,832
  • 11
  • 51
  • 67
0

Try synchronizing on the class object

public void print(){
    synchronized(B.class) {
         int i;
         for (i=0;i<1000;i++) {
             System.out.println(Thread.currentThread().getName() );
         }
    }
}
Andrey Cheboksarov
  • 649
  • 1
  • 5
  • 9
  • what is the meaning of B.class? Is it meaning that we have to lock it in class level? @andrey-cheboksarov – Sathiyakugan Nov 27 '16 at 12:48
  • @eagle Yes, that's it. You lock on the class object. With synchonized non-static method you lock on the instance. Instance in you case can mean b1 or b2, but they are independent. Another options is to have synchronized static method, it will work too – Andrey Cheboksarov Nov 27 '16 at 12:54
  • Thank you! I got great explanation! @andrey-cheboksarov – Sathiyakugan Nov 27 '16 at 15:59