同时执行成对线程

问题描述 投票:-4回答:2
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();
    }
}

在这里,我正在尝试前两个线程(比如对A)并发运行,接下来的两个线程(比如对B)只有在对A完成执行后才能并发运行。

此外,如果有人可以解释是否可以通过java.util.concurrent或threadgroup实现。我真的很感激任何帮助。

java multithreading synchronization java.util.concurrent
2个回答
0
投票
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();
}

0
投票

您可以使用CountDownLatch等待一定数量的线程调用countDown(),此时主线程可以继续。你将不得不对你的线程进行一些改动 - 也就是说,你需要将它们传递给它们,你需要让它们在完成工作时调用latch.countDown(),这样锁存器的计数最终会达到0。

所以你的主要类看起来像:

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

你的线程看起来像:

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

只有前两个线程完成后,锁存器才允许主线程继续并启动另外两个线程。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.