Domanda

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.

È stato utile?

Soluzione

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();
}

Altri suggerimenti

You can use a CountDownLatch to wait until a certain number of threads call countDown(), at which point the main thread can then continue. You will have to make some alterations to your threads -- namely, you'll need to pass them the latch, and you'll need to have them call latch.countDown() when they are done with their jobs so the latch's count will eventually reach 0.

So your main class would look something like:

final CountDownLatch latch = new CountDownLatch(2); // Making this final is important!
// start thread 1
// start thread 2
latch.await(); // Program will block here until countDown() is called twice
// start thread 3
// start thread 4

And your threads would look something like:

new Thread() {
    public void run() {
        // do work
        latch.countDown()
    }
}

And only once the first two threads finish will the latch allow the main thread continue and start the other two threads.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top