Mohi
Mohi

Reputation: 1808

How to run third thread when two thread done in Android

I'm writing an Android application that needs to work with threading.
In this app I have 3 threads that starts in the begin of the App.
Here is my code:

Thread t1,t2,t3;
protected void onCreate(Bundle savedInstanceState)
{

t1=new Thread(new Runnable()
{
    public void run()
    {
        //do some long stuffs
        t3.notify();
    }
});
t2=new Thread(new Runnable()
{
    public void run()
    {
        //do some long stuffs
        t3.notify();
    }
});
t3=new Thread(new Runnable()
{
    public void run()
    {
        this.wait();
        //run after t1 & t2 is done.
    }
});
t1.start();
t2.start();
t3.start();
}

now I want to sleep t3 thread and run it when t1 and t2 done their job.

Upvotes: 2

Views: 105

Answers (1)

MirecXP
MirecXP

Reputation: 443

Pass a t1, t2 reference to t3 and inside the t3.run() wait for the other threads:

t1.join();
t2.join();

Like this:

    final Thread t1, t2, t3;

    t1 = new Thread(new Runnable() {
        public void run() {
            //do some long stuffs
        }
    });

    t2 = new Thread(new Runnable() {
        public void run() {
            //do some long stuffs
        }
    });

    t3 = new Thread(new Runnable() {
        public void run() {
            try {
                t1.join();
                t2.join();
                // t1 & t2 have finished
                // continue with t3 stuff
            } catch (InterruptedException e) {
                //handle it
            }
        }
    });

    t1.start();
    t2.start();
    t3.start();

Upvotes: 1

Related Questions