简体   繁体   English

Java线程:如何同时执行一条语句

[英]Java Thread: How to execute a statement simultaneously

Consider I have a run method as below, I am trying to create four threads for MyThread. 考虑到我有一个运行方法如下,我试图为MyThread创建四个线程。 Statement 1 to 3 can either run at same time by threads or differently. 语句1到3可以同时在线程中运行,也可以不同地运行。 But I want Statement 4 to be executed by threads at a same time. 但是我希望语句4由线程同时执行。 Can I pool all threads before statement 4 and execute statement 4 at a same time by all threads? 我可以在语句4之前合并所有线程并由所有线程同时执行语句4吗?

class MyThread extends Thread
{ 
    public void run()
    {
        //Statement 1
    //Statement 2
    //Statement 3
    //Statement 4
    }

}

Use CyclicBarrier, it is best suited for your requirement. 使用CyclicBarrier,它最适合您的要求。

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierUsage {

    private static final int NUMBER_OF_THREADS = 2;

    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(NUMBER_OF_THREADS);

        Thread t1 = new Thread(new PrimaryParty(barrier));
        Thread t2 = new Thread(new PrimaryParty(barrier));

        t1.start();
        t2.start();    
    }
}

class PrimaryParty implements Runnable {

    private CyclicBarrier barrier;

    public PrimaryParty(CyclicBarrier barrier) {
        this.barrier = barrier;
    }

    @Override
    public void run() {
        //Statement 1
        //Statement 2
        //Statement 3

        try {
            barrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        }

        //Statement 4
    }
}

There are a few ways to do what you want. 有几种方法可以做您想要的。 Perhaps the easiest way is by using Java's implementation of Future . 也许最简单的方法是使用Java的Future实现。 You can define one (or more) Futures which will execute on separate threads, block until they are all done with Future.get() , and then complete your other tasks based on the results. 您可以定义一个(或多个)Future,它们将在单独的线程上执行,阻塞,直到它们全部由Future.get()完成,然后根据结果完成其他任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM