Java 从一个类运行两个方法

Java 从一个类运行两个方法,java,multithreading,Java,Multithreading,我有一个类,其中定义了两个方法ValidateA和ValidateB class A { ValidateA() { ///// } ValidateB() { //// } } 我想同时并行运行这两个步骤,并达到合并状态。如何继续使用线程?始终建议使用Java 5中引入的优秀执行器类。它们帮助您管理后台任务,并对类隐藏线程代码 像下面这样的方法可以奏效。它创建一个线程池,提交2个可运行类,每个类调用一个validate方法,然后等

我有一个类,其中定义了两个方法ValidateA和ValidateB

class A {
   ValidateA() {
        /////
    }

   ValidateB() {
        ////
    }
}

我想同时并行运行这两个步骤,并达到合并状态。如何继续使用线程?

始终建议使用Java 5中引入的优秀执行器类。它们帮助您管理后台任务,并对类隐藏线程代码

像下面这样的方法可以奏效。它创建一个线程池,提交2个可运行类,每个类调用一个validate方法,然后等待它们完成并返回。它使用一个结果对象,您将不得不弥补。它也可以是字符串或整数,具体取决于validate方法返回的内容

// reate an open-ended thread pool
ExecutorService threadPool = Executors.newCachedThreadPool();
// since you want results from the validate methods, we need a list of Futures
Future<Result> futures = new ArrayList<Result>();
futures.add(threadPool.submit(new Callable<Result>() {
    public Result call() {
       return a.ValidateA();
    } 
});
futures.add(threadPool.submit(new Callable<Result>() {
    public Result call() {
       return a.ValidateB();
    } 
});
// once we have submitted all jobs to the thread pool, it should be shutdown,
// the already submitted jobs will continue to run
threadPool.shutdown();

// we wait for the jobs to finish so we can get the results
for (Future future : futures) {
    // this can throw an ExecutionException if the validate methods threw
    Result result = future.get();
    // ...
}
了解


阅读本文可能是一个开始:可能与的重复对于使用ExecutorService的另一个更复杂的示例,请参阅AstartHere中对Objectwait的调用是什么?如果调用方没有意识到他需要在调用名称诱人的startHere之前调用ValidateA和ValidateB,那么这种设计就是强制执行NullPointerException的诱饵。对不起。固定的在那里运行Star将完成所有工作。
class A {
  public Thread t1;
  public Thread t2;
  CyclicBarrier cb = new CyclicBarrier(3);
  public void validateA() {
    t1=new Thread(){
       public void run(){
         cb.await();       //will wait for 2 more things to get to barrier
          //your code
        }};
    t1.start();
  }
  public void validateB() {
    t2=new Thread(){
       public void run(){
         cb.await();      ////will wait for 1 more thing to get to barrier
          //your code
        }};
    t2.start();
  }
  public void startHere(){
        validateA();
        validateB();
        cb.wait();      //third thing to reach the barrier - barrier unlocks-thread are                 running simultaneously
  }
}