Search code examples
javamultithreadingsynchronizationjava.util.concurrent

Execute pairwise threads concurrently


class A
{
    public void func()
    {
        new Thread()
        {
            public void run()
            {
                // statements
            }
        } .start();
        new Thread()
        {
            public void run()
            {
                // statements
            }
        } .start();
        new Thread()
        {
            public void run()
            {
                // statements
            }
        } .start();
        new Thread()
        {
            public void run()
            {
                // statements
            }
        } .start();
    }
}

Here, I'm trying the first two threads (say pair A) to run concurrently and the next two threads (say pair B) to run concurrently only after pair A has finished executing.

Also if anybody can explain if it can be achieved via java.util.concurrent or threadgroup. I'll really appreciate any help done.


Solution

  • public void func()
    {
        Thread a = new Thread()
        {
            public void run()
            {
                // statements
            }
        }
        Thread b = new Thread()
        {
            public void run()
            {
                // statements
            }
        }
        a.start();
        b.start();
        a.join();  //Wait for the threads to end();
        b.join();
        new Thread()
        {
            public void run()
            {
                // statements
            }
        } .start();
        new Thread()
        {
            public void run()
            {
                // statements
            }
        } .start();
    }