Sunny Gupta
Sunny Gupta

Reputation: 7067

Ordering the execution of Threads in Java

Please have a look at the code below:

Class A

package generalscenarios;

public class A implements Runnable{

    public void run(){

        System.out.println("dsad");

    }

}

Class B

package generalscenarios;


public class B {


    public static void main(String[] args) throws InterruptedException {

        A a1  = new A();
        Thread a = new Thread(a1);
        a.start();
        System.out.println("hi");
    }
}

When I execute the class B, My thread a will be started by the main thread, And hi will be printed on console by the main thread. But the order of printing "hi" and "dsad" is not determined.

I want that "hi" should be printed after "dsad".

The solution that I thought of is to take a shared variable between main thread and thread "a". Main thread will wait on that variable till the time thread "a" notifies him.

Class A

package generalscenarios;

public class A implements Runnable{

    public void run(){

        System.out.println("dsad");
        synchronized (this) {
            this.notify();  
        }


    }

}

Class B

package generalscenarios;


public class B {


    public static void main(String[] args) throws InterruptedException {

        A a1  = new A();
        Thread a = new Thread(a1);
        a.start();
        synchronized (a1) {
            a1.wait();
        }
        System.out.println("hi");
    }
}

Please suggest me if my thinking is valid. Please suggest any other way of achieving this.

Upvotes: 2

Views: 242

Answers (1)

Subir Kumar Sao
Subir Kumar Sao

Reputation: 8411

You can try something like

public static void main(String[] args) throws InterruptedException {

    A a1  = new A();
    Thread a = new Thread(a1);
    a.start();
    a.join();
    System.out.println("hi");
}

Do read Thread.join() and also read the complete reference of Thread.

Upvotes: 6

Related Questions